【问题标题】:No such element exception when reading from a text file [closed]从文本文件读取时没有这样的元素异常[关闭]
【发布时间】:2016-03-20 19:45:04
【问题描述】:

我正在尝试从文本文件中读取数据并使用该数据来恢复保存游戏。然而,问题是当它到达从文件中读取的第一行代码时,它会抛出 no such element 异常吗?谁能给我一个暗示为什么会这样。我已经检查了文本文件,并且可以从中读取数据。

下面是使用的代码:

public void readSave() {

            int p1Turn = 0;
            int p2Turn = 0;

            try {
                FileReader fr = new FileReader("snorkels.txt");
                BufferedReader reader = new BufferedReader(fr);
                String line = reader.readLine();
                Scanner scan = null;

                int playerNumber = 0;


                while (line != null) {
                    scan = new Scanner(line);
                    playerNumber = scan.nextInt(); // No such element exception 

                    if (playerNumber == 1) {
                        player1.setName(scan.next());
                        player1.setColour(scan.next());
                        p1Turn = scan.nextInt();
                    }

                    if(playerNumber == 2){
                        player2.setName(scan.next());
                        player2.setColour(scan.next());
                        p2Turn = scan.nextInt();
                    }

                    line = reader.readLine();
                }


                reader.close();

            } catch (FileNotFoundException e) {
                System.out.println("Couldnae find the file");
            } catch (IOException e) {
                System.out.println("Wee problem reading from file");
            }


        }

当我尝试读取第一个 int 时抛出异常。

文本文件包含以下数据:

1 个插孔 P 0

2 人工智能 G 0

【问题讨论】:

  • 那是一堵不可读且未格式化的代码墙。没有人会想读那个。请通过How to Askminimal reproducible example
  • 使用调试器,下一行断点,然后查看line的值。它显然不包含您认为的内容。

标签: java exception io


【解决方案1】:

例外是因为文件,你之间有一个空行 1 jack P 02 AI G 0,因此当您的扫描仪尝试获取空行的 nexInt 时会引发异常。

删除它,它会工作。

【讨论】:

    【解决方案2】:

    您可能不应该使用扫描仪来获取您的号码。

    你有你保存文件的行作为一个字符串,你应该通过拆分你的字符串来获得不同的元素。

    int playernumber = Integer.parseInt(line.split(" ")[0]);
    int turn = Integer.parseInt(line.split(" ")[3]);
    

    希望对您有所帮助...

    【讨论】:

    • 我试过这样做,但它也抛出了 no such element 异常。我在拆分字符串之前打印了该行的内容,这完全符合我的预期 - “1 scott P 0”。很困惑为什么“int playernumber = Integer.parseInt(line.split(””)[0]);”如果要读取 int 会导致异常?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多