java Scanner next方法 nextLine方法
// 创建Scanner对象
Scanner scan = new Scanner(System.in);
// 阻塞等待用户输入数据
if (scan.hasNext()) {
String text = scan.next();
System.out.println("输入的数据为:" + text);
}
// 关闭
scan.close();
next注意点:
(1).next方法是阻塞的,直到它等到用户输入数据
(2).next方法遇到空白字符串后的字符都会丢弃(不知道我解释是否准确),例如aaaaaa f只能输出例如aaaaaa
而nextLine方法是没有此问题的
// 创建Scanner对象
Scanner scan = new Scanner(System.in);
// 阻塞等待用户输入数据
if (scan.hasNextLine()) {
String text = scan.nextLine();
System.out.println("输入的数据为:" + text);
}
// 关闭
scan.close();
Scanner对象还支持对输入数据类型的支持,例如
// 创建Scanner对象
Scanner scan = new Scanner(System.in);
// 定义接收字符串
int number = 0;
// 输入整数测试
if (scan.hasNextInt()) {
number = scan.nextInt();
System.out.println("输入的是整数数据:" + number);
} else {
System.out.println("输入的不是整数");
}
// 关闭
scan.close();