Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

前端 未结 12 1391
灰色年华
灰色年华 2020-12-01 10:18

How does this program actually work...?

import java.util.Scanner;

class string
{
    public static void main(String a[]){
        int a;
        String s;
          


        
12条回答
  •  青春惊慌失措
    2020-12-01 10:40

    .nextInt() gets the next int, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.

    You can insert another .nextLine() after you get the int to fix this. Or (I prefer this way), read the int in as a string, and parse it to an int.

提交回复
热议问题