简体   繁体   English

while循环为我提供了“ <identifier expected> ”错误

[英]While loop gives me an “<identifier expected>” error

The goal is to fill an ArrayList with custom Country objects made up of information from a separate text file. 目标是用由来自单独文本文件的信息组成的自定义Country对象填充ArrayList。 The while loop gives me the "identifier expected" error, and I'm at my wit's end trying to fix it. while循环为我提供了“期望的标识符”错误,而我正竭尽全力解决此问题。

import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;

public class Driver {

    public static void main(String[] args) {
        //Instance variables
        Scanner sc;
        Country next = new Country();
        String reader;
        int size;
        ArrayList<Country> ledger = new ArrayList<Country>();

        //Suppressing this exception because I know it's there.
        @SuppressWarnings("unreported exception FileNotFoundException; must be caught or declared to be thrown")
        sc = new Scanner(new File("testLedger.txt"));

        //"<identifier> expected" error
        while (sc.hasNext()) {
            next.setName(sc.nextLine());
            next.setFaith(sc.nextLine());
            next.setInfo(sc.nextLine());
            next.setOrder(sc.nextInt());
            ledger.add(next);
        }

        //Test accessor methods and filling of the ArrayList
        for (int i = 0; i < ledger.size(); i++) {
            System.out.println(ledger.get(i));
        }
    }
}

First, your code will not compile. 首先,您的代码将无法编译。 You need to handle the exceptions. 您需要处理异常。 As in this case you are just running a test, you can use a Throw in the main method. 在这种情况下,您只是在运行测试,因此可以在main方法中使用Throw。

    try {
        sc = new Scanner(new File("testes.txt"));

        while (sc.hasNext()) {

            next.setName(sc.nextLine());
            next.setFaith(sc.nextLine());
            next.setInfo(sc.nextLine());
            next.setOrder(sc.nextInt());
            ledger.add(next);
        }
    } catch (FileNotFoundException e) {
        System.out.println(e);
    }

Second, look at the setters of your Country class and see if the method types are compatible with what you are using in the while. 其次,查看Country类的设置器,看看方法类型是否与您所使用的一段时间兼容。

For example: 例如:

sc.nextLine () // will return a String
sc.nextInt () // will return an int

your setters should be compatible with this 您的二传手应该与此兼容

public void setOrder(int order){
    this.order = order;
}

and Finally, as mentioned by @Dawood in comments, you need do see stackoverflow.com/q/13102045 最后,正如@Dawood在评论中提到的,您需要查看stackoverflow.com/q/13102045

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM