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():
- You must read valid characters before you can end the input
- For blanks encountered before entering valid characters, the next() method will automatically remove them
- Only after valid characters are entered, the blank entered after it is used as a separator or terminator
- next() cannot get a string with spaces
nextLine():
- With Enter as the terminator, that is, the nextLine() method returns all the characters before the carriage return
- Space character