Java Scanner sc.nextLine() 的问题;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2444343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:45:39  来源:igfitidea点击:

Problem with Java Scanner sc.nextLine();

javajava.util.scanner

提问by Jonathan B

sry about my english :)
Im new to Java programming and i have a problem with Scanner. I need to read an Int, show some stuff and then read a string so i use sc.nextInt();show my stuff showMenu();and then try to read a string palabra=sc.nextLine();

sry 我的英语 :)
我是 Java 编程的新手,我在使用 Scanner 时遇到了问题。我需要读取一个 Int,显示一些东西,然后读取一个字符串,所以我使用sc.nextInt(); 显示我的东西showMenu(); 然后尝试读取字符串palabra=sc.nextLine();

Some one told me i need to use a sc.nextLine(); after sc.nextInt(); but i dont understand why do you have to do it :(

有人告诉我我需要使用 sc.nextLine(); 在 sc.nextInt() 之后;但我不明白你为什么要这样做:(

Here is my code:

这是我的代码:

public static void main(String[] args) {
    // TODO code application logic here
    Scanner sc = new Scanner(System.in);
    int respuesta = 1;

    showMenu();
    respuesta = sc.nextInt();
    sc.nextLine(); //Why is this line necessary for second scan to work?

    switch (respuesta){
        case 1:
            System.out.println("=== Palindromo ===");
            String palabra = sc.nextLine();
            if (esPalindromo(palabra) == true)
                System.out.println("Es Palindromo");
            else
                System.out.println("No es Palindromo");
        break;
    }


}

Ty so much for your time and Help :D

非常感谢您的时间和帮助:D

采纳答案by Ben S

nextInt()only reads in until it's found the int and then stops.

nextInt()只读入直到找到 int 然后停止。

You have to do nextLine()because the input stream still has a newline character and possibly other non-int data on the line. Calling nextLine()reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.

你必须这样做,nextLine()因为输入流仍然有一个换行符和可能的其他非整型数据。CallingnextLine()读取剩下的任何数据,包括用户在输入 int 和输入 String 之间按下的 enter。

回答by Fadi Hanna AL-Kass

When you input a value (whether String, int, double, etc...) and hit 'enter,' a new-line character (aka '\n') will be appended to the end of your input. So, if you're entering an int, sc.nextInt()will only read the integer entered and leave the '\n'behind in the buffer. So, the way to fix this is to add a sc.nextLine()that will read the leftover and throw it away. This is why you need to have that one line of code in your program.

当您输入一个值(无论是Stringintdouble等...)并按“回车”时,一个换行符(又名'\n')将附加到您输入的末尾。因此,如果您输入的是 int,sc.nextInt()则只会读取输入的整数并将其'\n'留在缓冲区中。因此,解决此问题的方法是添加一个sc.nextLine()将读取剩余部分并将其丢弃的方法。这就是为什么您需要在程序中包含这一行代码的原因。