java.util.NoSuchElementException错误,scan.next()问题

时间:2019-07-08 07:06:23

标签: java

创建一种将文本追加到现有文件中的方法,但是我不断收到错误消息

请注意,我只粘贴了一个方法,而不是整个代码。

错误:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Roster.Team.add(Team.java:47)
at Roster.Main.main(Main.java:22)

代码:

    public void add(){
    System.out.println("Enter the name of the file that you wish to add information to: ");
    String name;
    name = scan.nextLine();
    try{
       BufferedWriter writer = new BufferedWriter(new FileWriter(name, true));
        for(Player p : x)
            if(p != null){
                writer.write(p + "\n");
                writer.newLine();
            }
        writer.close();
    } catch (IOException e) { }
}

1 个答案:

答案 0 :(得分:-1)

您收到此错误,因为在扫描仪中未找到任何行,请在代码中添加check

if (scan.hasNextLine()) {
    System.out.println("Enter the name of the file that you wish to add information to: ");
    String name;
    name = scan.nextLine();
    try{
       BufferedWriter writer = new BufferedWriter(new FileWriter(name, true));
        for(Player p : x)
            if(p != null){
                writer.write(p + "\n");
                writer.newLine();
            }
        writer.close();
    } catch (IOException e) { 
        // it is better to log exception here
        e. printStackTrace();
    }
} else {
    System.out.println("Scanner has no lines to read.");
}

检查tutorial如何在Java中使用扫描仪。