Usage of next() and nextLine()

Import package

package com.HePing.scanner;

import javax.sound.midi.Soundbank;
import java.util.Scanner;

Usage of next():

Create a scanner object to receive keyboard data
Scanner scanner = new Scanner(System.in);

        //判断用户有没有使用输入字符串
        if(scanner.hasNext()){
    
    
            //使用next方式接收
            String str = scanner.next();    //程序会等待用户输入完毕
            System.out.println("输入的内容为:"+str);
        }

Usage of nextLine():

Create a scanner object to receive keyboard data
Scanner scanner = new Scanner(System.in);

        //判断是否还有输入
        if(scanner.hasNextLine()){
    
          //以Enter为结束符
            String str = scanner.nextLine();
            System.out.println("输出的内容为:"+str);
        }

Close the program to save memory:
scanner.close();

The difference between the next() method and nextLine() method of the Scanner class

next():

  1. You must read valid characters before you can end the input
  2. For blanks encountered before entering valid characters, the next() method will automatically remove them
  3. Only after valid characters are entered, the blank entered after it is used as a separator or terminator
  4. next() cannot get a string with spaces

nextLine():

  1. With Enter as the terminator, that is, the nextLine() method returns all the characters before the carriage return
  2. Space character

Guess you like

Origin blog.csdn.net/qq_45361567/article/details/112620611