首页 > 解决方案 > 为什么我不能在 try/catch 中输入多个输入?

问题描述

我在尝试在 try/catch 语句中的 do-while 循环中获取多个输入时遇到了困难:

FileOutputStream file;
PrintStream pen;
String name;
char exitInput;

try {
        file = new FileOutputStream("names.txt");
        pen = new PrintStream(file);
        
        do {

            System.out.print("Enter a name: ");
            name = input.nextLine();
            
            pen.print(name + "\n");
            
            System.out.println("Would you like to enter more names?");
            System.out.print("Option(y/n): ");
            exitInput = input.next().charAt(0);
        
        } while(exitInput != 'n');
        
        pen.close();
    
    } catch(IOException exc) {
        
        System.out.println("<INPUT ERROR>");
    
    }

当我运行这段代码时,它会问我一个名字,然后问我是否要输入更多的名字。如果我选择是,那么它只会跳过“name = input.nextLine();” 行和显示:

Enter a name: Would you like to enter more names?
Option(y/n):

键入两个“name = input.nextLine();”时问题似乎得到解决,但是,这不是一个很好的解决方案。

标签: javatry-catchjava.util.scanner

解决方案


input.next()只消耗一个令牌,而不是整行。当您调用input.nextLine()它时,会消耗该行的其余部分。

修复该替换input.next()input.nextLine().


推荐阅读