【发布时间】:2015-12-10 23:02:29
【问题描述】:
所以现在当我尝试使用不返回任何值(无效)并且接受参数ArrayList<E> fileList 的方法时,我遇到了语法错误。我的目标是接收一个包含 String 和 Integer 对象的文本文件,如果在 remove 方法中找到一个 Integer ,那么它将从列表中删除。这样它只会在最后留下字符串。这是显示文件读取和我尝试使用的 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) 收到语法错误。
【问题讨论】:
-
请务必逐字逐句地发布完整的错误消息。
-
请注意,
read.next()总是 返回String。该列表中永远不会有任何Integer对象。 -
这段代码没有多大意义。 Scanner.next() 返回一个字符串,而不是一个 E。所以列表永远不会包含任何整数,并且该方法应该返回一个 List
。您不应该忽略编译器警告。他们告诉你你的代码是错误的。 -
有没有办法判断它是否是一个整数,我被困在如何正确地让它工作。
-
它永远不是整数。 next() 返回一个字符串。我不知道你想在这里实现什么。
标签: java string for-loop arraylist integer