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

Getting a Syntax error when trying to use a method using ArrayLists?

所以现在当我尝试使用一个没有 return 任何值(无效)并且接受参数 ArrayList<E> fileList 的方法时,我遇到了语法错误。我的目标是接收一个包含字符串和整数对象的文本文件,如果在 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) 处收到语法错误。

将 removeInts 的签名更改为通用的:

public <E> void removeInts(ArrayList<E> fileList)

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

鉴于您最后的评论:

I am trying to be able to remove ints from a text file, only leaving strings left. Say for example I had a text file that said "A B C 1 2 3", first the Scanner (I need to use a scanner) would take in the file, and put it into an ArrayList. Then when I use the remove method it would take out all values that are Integers, and leave alone the Strings. The final output at the end would be "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]