尝试使用ArrayLists方法时出现语法错误?

时间:2015-09-14 20:28:28

标签: java string for-loop arraylist integer

所以现在我在尝试使用不返回任何值(无效)的方法时收到语法错误,并且接受参数ArrayList<E> fileList。我的目标是接受一个包含String和Integer对象的文本文件,如果找到一个Integer,则在remove方法中,它将从列表中删除。这样它只会在最后离开字符串。以下代码显示了文件的读取以及我尝试使用的removeInts方法:

@SuppressWarnings("unchecked") //IDE told me to add this for adding objects to the ArrayList
public <E> ArrayList<E> readFile(){
    ArrayList<E> fileList = new ArrayList<E>();
    try {
        Scanner read = new Scanner(file); //would not let me do this without error handling
        while(read.hasNext()){ //while there is still stuff to add it will keep filling up the ArrayList
            fileList.add((E)read.next());
        }
    } catch (FileNotFoundException e) {
        System.out.println("File not found!");
        e.printStackTrace();
    }
    removeInts(fileList);
    return fileList;    
}

public void removeInts(ArrayList<E> fileList){
    for(int i = 0; i < fileList.size(); i++){
        if(fileList.get(i) instanceof Integer){
            fileList.remove(i);
        }
        else{
            //does nothing, does not remove the object if it is a string
        }
    }

我在removeInts(fileList)收到语法错误。

2 个答案:

答案 0 :(得分:3)

正如其他人指出的那样,您的列表永远不会包含Integer,因为next()会返回String

鉴于你的上次评论:

  

我正在尝试从文本文件中删除整数,只留下字符串。比方说,我有一个说"A B C 1 2 3"的文本文件,首先Scanner(我需要使用扫描仪)将接收文件,并将其放入ArrayList。然后当我使用remove方法时,它会取出所有的整数值,而不用单独的字符串。最后的结果是"A B C"

不要先将它们作为整数加载,然后将其删除。相反,不要加载它们:

List<String> list = new ArrayList<>();
try (Scanner sc = new Scanner("A B C 1 2 3")) {
    while (sc.hasNext()) {
        if (sc.hasNextInt())
            sc.nextInt(); // get and discard
        else
            list.add(sc.next());
    }
}
System.out.println(list);

输出

[A, B, C]

答案 1 :(得分:2)

将removeInts的签名更改为通用:

public <E> void removeInts(ArrayList<E> fileList)
相关问题