如何在其他方法中使用公共静态扫描器?(nextLine());.


import java.util.Scanner;
public class mainClass{
    static public Scanner keyboard = new Scanner(System.in);
    public static void main (String [ ] args)
    {
        anotherMethod();
    }
    static public void anotherMethod()
    {
        String sentence;
        String answer;
        do{
            System.out.println("Lets read a sentence: ");
            String Sentence = keyboard.nextLine();
            System.out.println("The sentence read: " + sentence);
            System.out.println("Do you want to repeat?");
            answer = keyboard.next();
        } while (answer.equalsIgnoreCase("yes");
    }
}

结果是,在第一次运行后,程序显示"Lets read a sentence:"并且"The sentence read: ",而不让我输入句子。

我想知道解决这个问题的简单方法。

这是

正在发生的事情:程序读取带有nextLine的输入,然后提示是/否,此时您键入yes,然后按 Enter 键。现在Scanner 的缓冲区包含以下四个字符:

'y' 'e' 's' 'n'

当你调用 next() 时,Scanner读取最多 'n' 个字符作为分隔符。字母将从缓冲区中删除,因此"yes"成为next()的结果。但是,'n'没有被采取!它保留在缓冲区中以供下一次Scanner调用。

现在循环进入下一次迭代,程序提示输入更多输入,并调用 nextLine() 。还记得缓冲区中的'n'吗?这就是您的程序将立即读取的内容,结束输入。

您可以通过将next()调用替换为 nextLine() 调用来解决此问题。

您还需要使用 nextLine() 方法来收集answer字符串。

answer = keyboard.nextLine();

否则,next() 调用仅返回字符串yes,但会留下一个新行字符,该字符会在while循环的下一次迭代中被扫描,而不会让您有机会输入某些内容。

最新更新