有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。NoTouchElementException错误,扫描。下一个问题

创建一个将文本附加到现有文件的方法,但我一直收到一个错误

请注意,我只粘贴了一个方法,而没有粘贴整个代码

错误:

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) 个答案

  1. # 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中使用扫描仪