next()和hasNext()? nextLine()和hasNextLine()?
java通过Scanner类来获取用户输入,形式如下:
Scanner scanner = new Scanner(System.in);
Scanner类的next()和nextLine()方法输入字符串,HasNext()和HasNextLine()判断是否还有输入的数据。
next() 输入数据
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 从键盘接收数据
// next方式接收字符串
System.out.println("next方式接收:");
// 判断是否还有输入
if (scan.hasNext()) {
String str1 = scan.next();
System.out.println("输入的数据为:" + str1);
}
scan.close();
}
}
NextLine() 输入数据
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 从键盘接收数据
// nextLine方式接收字符串
System.out.println("nextLine方式接收:");
// 判断是否还有输入
if (scan.hasNextLine()) {
String str2 = scan.nextLine();
System.out.println("输入的数据为:" + str2);
}
scan.close();
}
}
总结
next():
- 读取到有效字符后才结束输入。
- 对输入有效字符前遇到的空白,next()方法会自动去掉空白。
- 只有输入有效字符后才将其后面输入的空白作为分隔符或结束符。
- next()方法不能得到带有空白的字符串。
NextLine()
- NextLine()方法可以得到输入回车符前的所有字符(包括空白)。