【问题标题】:Getting a Syntax error when trying to use a method using ArrayLists?尝试使用使用 ArrayLists 的方法时出现语法错误?
【发布时间】: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


【解决方案1】:

将 removeInts 的签名改为泛型:

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

【讨论】:

  • 哇,这很简单。感谢您的帮助。
  • 我很乐意提供帮助!如果解决了请采纳答案
【解决方案2】:

正如其他人指出的那样,您的列表永远不会包含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]

【讨论】:

  • 它是否有原因首先输出这个,然后是文本文件中的内容? [{\rtf1\ansi\ansicpg1252\cocoartf1348\cocoasubrtf170, {\fonttbl\f0\fswiss\fcharset0, Helvetica;}, {\colortbl;\red255\green255\blue255;}, \margl1440\margr1440\vieww10800\viewh8400\viewkind0 , \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural, \f0\fs24, \cf0,
  • @FyreeW 您的文件已保存为RTF file。将其保存为纯文本文件。
  • 将其更改为 .txt 文件,之后开始工作。感谢@Andreas 指出这一点。
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2022-06-15
  • 2020-07-31
  • 1970-01-01
  • 2019-11-24
相关资源
最近更新 更多