import java.util.*;
public class InPutException {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (Incorrect input: an integer is required)");
input.nextLine();
}
}while(continueInput);
}
上面input.nextLine()语句的作用是什么
public class InPutException {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (Incorrect input: an integer is required)");
input.nextLine();
}
}while(continueInput);
}
上面input.nextLine()语句的作用是什么
一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。Scanner 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。例如,以下代码使用户能够从 System.in 中读取一个数: Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
LZ问nextLine()的作用,API上也有解释 我就不贴出来了。这个方法的应用场景 我也不清楚。等待...
楼主可以把这条语句注释掉:
//continueInput = false;
随便输入一些整数,中间空格分开,试试。比如:123 345 456
再输入出现异常的数据如:123 456 weq 567 看看结果。同样的数据,把那条语句:
input.nextLine();
注释掉,再输入,你就知道为什么了。
System.out.println(temp);
当发生异常时,读取刚才输入的“一行字符串”