我正在尝试编写一个程序,该程序从用户输入的扫描仪中读取所有单词,将它们放入 ArrayList 调用方法中,并打印长度小于 5 的所有单词的列表。是的,我可以在一个程序中编写它,但分配的目的是使用接口和继承。我编写了一个程序,将用户输入循环到对象数组中。我写了一个接口(这不能改变),我实现了一个类,它扫描数组中的单词并根据单词是少于五个还是多于五个字母给出一个布尔值。我编写了一个从类中获取答案并创建一个新的对象 ArrayList 的方法。如果单词少于五个字母,则将其添加到数组中。我正在尝试将该方法调用到我的主要方法中,但我得到一个“过滤器是抽象的” “无法实例化”错误...但我的界面不是抽象的?我不知道如何解决它,它让我发疯......非常感谢任何帮助。谢谢!
public interface Filters
{
boolean accept(Object x);
//this interface cannot be changed.
}
public class SWordFilter implements Filters
{
//This is my subclass for the interface
public boolean accept(Object x)
{
String y =(String) x;
boolean accept=false;
if (y.length()< 5)
accept=true;
return accept;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class MyHomework
{
//this is my main and my method. I cannot call the method.
public static void main(String[] args)
{
ArrayList<Object> names=new ArrayList<Object>();
Scanner in=new Scanner(System.in);
int i=0;
while(i<5)
{
System.out.println("Enter the words");
names.add(in.next());
i++;
}
Filters tran= new Filters(names);
Object result=collectAll(names,tran);
}
public static ArrayList<Object> collectAll (ArrayList<Object> list, Filters f)
{
ArrayList<Object> result= new ArrayList<Object>();
for (int x=0; x<5; x++)
{
if (f.accept(list.get(x)))
{
result.add(list.get(x));
}
else
{
System.out.print("the word is too long");
}
//SWordFilter julie= new SWordFilter();
//System.out.print(julie.accept(names.get(j)));
}
return result;
}
}