如何编写循环访问文本文件并使用对象的 equals 方法将所有元素添加到 arrayList 的方法



>我正在尝试创建 Line 对象并将它们添加到数组列表中。我遇到的问题是排除任何彼此相似的行。我已经创建了一个 equals 方法,用于比较两条线以确定它们是否相等。我在使用 while 循环时遇到问题。我没有错误消息。它编译得很好。它只是不会从文本文件中读取。我被困住了,不知道从这里还能去哪里。

public void read( File fileName ) throws Exception
{
    reader = new Scanner(fileName);

    //---------------------
    //Have to read the first number before starting the loop
    int numLines = reader.nextInt();
    lines = new ArrayList <Line> (numLines);
    //This loop adds a new Line object to the lines array for every line in the file read.
    while( reader.hasNext() ) {
        for( int i = 0; i < numLines; i++ ) {
            int x = reader.nextInt();
            int y = reader.nextInt();
            Point beg = new Point(x,y);
            x = reader.nextInt();
            y = reader.nextInt();
            Point end = new Point(x,y);
            String color = reader.next();
              Line l =  new Line( beg, end, color );
              if (l.equals(lines.get(i)))
                  break;
              else
                  lines.add(i, l);

        }
    }
    //Print the action to the console
    System.out.println( "reading text file: " + fileName );
    reader.close();
}

lines是一个ArrayList。您无法像在代码中那样通过lines(i)来访问 ArrayList 的元素i;你需要做lines.get(i).

第一个异常已经被其他人解释过了,所以我将解释另一个:

Void methods cannot return a value

您创建了以下方法:

public void read( File fileName ) throws Exception

while循环中,您可以执行以下操作:

    if (this.lines(i).equals(lines(i)))
        return null;
    else
        lines.add(i, l);

你返回null,虽然你可以在while循环中使用return,但如果将方法声明void,则无法这样做。您应该改用break

例外很明显,你不能在 void 函数中返回任何内容。因此,只需将您的代码修改为:

  Line l =  new Line( beg, end, color );
  //if not equals, add it
  if (!this.lines(i).equals(lines.get(i))){
            //TODO: add to you collection
  }

我希望它有所帮助

你不应该在没有返回值(void)的方法上"返回null"。您可以改用"返回"。但是,我认为您想要的是"继续"。还可以考虑使用 HashSet 代替数组列表,这样您就不需要再检查相等性了,因为哈希集不允许重复。

最新更新