我尝试捕获最终有效的异常,但现在我需要弄清楚如何使其循环。那么,我怎样才能将用户输入(int select)转到循环外部?我可以尝试创建一个新功能,这可能会起到作用。
do {
System.out.print("How many integers shall we compare? (Enter a positive integer): ");
try {
select = intFind.nextInt();
} catch (InputMismatchException e) {
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
intFind.nextLine();
}
} while (select < 0);
然后
do
{
System.out.print("How many integers shall we compare? (Enter a positive integer): ");
try {
b = Get();
}
catch (InputMismatchException e) {
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
intFind.nextLine();
} copySel = b;
}while(select < 0);
和
static int Get()
{
Scanner intFind = new Scanner(System.in);
int select;
select = intFind.nextInt();
return select;
}
答案 0 :(得分:0)
要使其循环,请确保将select
初始化为小于0的值。但最好是条件select < 2
,因为至少比较值更有意义
创建一个类似
的方法private int[] promptIntegers(int numberOfIntegers, Scanner sc) {
int[] integers = new int[numberOfIntegers];
//read ints
//return the array
}
并将其称为
select = intFind.nextInt();
int[] integers = promptIntegers(select, sc);
//do the comparison among the integers