How can I read input from the console using the Scanner class in Java?

前端 未结 15 1988
我寻月下人不归
我寻月下人不归 2020-11-21 06:19

How could I read input from the console using the Scanner class? Something like this:

System.out.println(\"Enter your username: \");
Scanner = i         


        
15条回答
  •  旧巷少年郎
    2020-11-21 07:08

    There is problem with the input.nextInt() method - it only reads the int value.

    So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().

    Try it like that:

     System.out.print("Insert a number: ");
     int number = input.nextInt();
     input.nextLine(); // This line you have to add (it consumes the \n character)
     System.out.print("Text1: ");
     String text1 = input.nextLine();
     System.out.print("Text2: ");
     String text2 = input.nextLine();
    

提交回复
热议问题