Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Scanner sc.nextLine()存在问题;_Java_Java.util.scanner - Fatal编程技术网

Java Scanner sc.nextLine()存在问题;

Java Scanner sc.nextLine()存在问题;,java,java.util.scanner,Java,Java.util.scanner,关于我的英语:) 我是Java编程新手,扫描器有问题。我需要读取一个Int,显示一些内容,然后读取一个字符串,所以我使用sc.nextInt()显示我的东西显示菜单()然后尝试读取字符串palabra=sc.nextLine() 有人告诉我我需要使用sc.nextLine();在sc.nextInt()之后;但我不明白你为什么要这么做:( 这是我的密码: public static void main(String[] args) { // TODO code application l

关于我的英语:)
我是Java编程新手,扫描器有问题。我需要读取一个Int,显示一些内容,然后读取一个字符串,所以我使用sc.nextInt()显示我的东西显示菜单()然后尝试读取字符串palabra=sc.nextLine()

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

这是我的密码:

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;
    }


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

nextInt()
只在找到int之前读取,然后停止


您必须执行
nextLine()(无论是
String
int
double
,等等)并点击“回车”,一个新行字符(aka
'\n'
)将附加到输入的末尾。因此,如果您输入的是int,
sc.nextInt()
将只读取输入的整数,并将
'\n'
留在缓冲区中。因此,解决此问题的方法是添加
sc.nextLine()
这将读取剩余内容并将其扔掉。这就是为什么您需要在程序中使用这一行代码的原因。

我第一次遇到这个问题时,它也难住了我,但一旦您知道它为什么有意义!很高兴知道我不是唯一的一个:D