[英]Try & Catch multiple input statements
我正在尝试捕获多个输入语句的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);
}
}
我不确定什么对您不起作用,但是这是我将如何实现这一点:
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] ) );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.