我试图捕获多个输入语句的InputMismatchException
。我意识到它不能正常工作。我应该为每个输入语句单catch
和try
吗?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner input = new Scanner(System.in);
boolean tue = true;
int inputNum=0;
int inputNum2=0;
int inputNum3=0;
do {
try {
System.out.println("Enter a number");
inputNum = input.nextInt();
System.out.println("Enter another number: ");
inputNum2 = input.nextInt();
System.out.println("Enter another number");
inputNum3 = input.nextInt();
tue = false;
} catch (InputMismatchException e) {
input.nextLine();
System.out.println("Enter the require text");
}
}while (tue);
System.out.println(inputNum + " "+ inputNum2 + " "+ inputNum3);
}
}
答案 0 :(得分:0)
我不确定什么不适合你,但这是我将如何实现这一点:
Scanner input = new Scanner(System.in);
int[] inputs = new int[3];//create array for the # of inputs
for ( int i = 0; i < inputs.length; ) {
try {
System.out.println( "Enter Num " + ( i + 1 ) );
inputs[i] = input.nextInt();
i++;//only increment if the line above doesnt raise error
} catch ( InputMismatchException e ) {
input.nextLine();
System.out.println( "Only integers allowed, try again" );
}
}
input.close();
System.out.println( inputs[0] + " " + inputs[1] + " " + inputs[2] );
打印整个阵列:
for ( int i = 0; i < inputs.length; i++ ) {
System.out.println( String.format( "Input %s was %s", i + 1, inputs[i] ) );
}