The difference between next and nextLine in Scanner

Difference one:

  	    String st1 = scanner.nextLine();
        String st2 = scanner.next();

        System.out.println("nextLine方式输入:" + st1);
        System.out.println("next方式输入:" + st2);

operation result:

It can be seen that the character string entered in the nextLine mode can contain spaces, nextLine uses carriage return as the sign of the end of input, and next has spaces or

Difference two:

  	    int num = scanner.nextInt(); // 8
        String st = scanner.nextLine(); // hello java

        System.out.println(num + "===========" + st); // 8 =======

operation result:

 insert image description here

Conclusion: It can be seen that before I enter the string, the input will automatically end. nextLine will read carriage return as its value

Solve the above problems:

   	    int num = scanner.nextInt(); 
        scanner.nextLine(); //读取回车
        String st = scanner.nextLine(); 
        System.out.println(num + "===========" + st);

Summarize:

 

Guess you like

Origin blog.csdn.net/weixin_64443786/article/details/130764566