如何在java中的try-catch语句中放入循环



我的程序假设当用户输入整数时,将随机数数组添加10,随机数数组将被显示并在第一个数组下添加10,如果用户没有输入int,则try-catch语句会捕捉到显示错误消息的错误,所以我想做的是在try-catch语句中添加一个循环,让用户在不输入int的时候输入int——这是我迄今为止尝试过的,但没有起到的作用

public class tryandcatch {
public static void main(String[] args) {
int[] tab=new int[10];
int i;
Scanner inp=new Scanner(System.in);
while(true) {
try{
System.out.println("Please enter an integer number");
i=inp.nextInt(); 

for(i=0;i<tab.length;i++){
tab[i]=((int)(Math.random()*100));
System.out.print(tab[i]+" ");
}
addTen(tab);
System.out.print("n");
for(i=0;i<tab.length;i++)System.out.print(tab[i]+" ");
break;
}
catch(InputMismatchException e){
System.out.println("The number must be integer");
i=inp.nextInt(); 

}
}
}

static void addTen(int[] x){
int i;
for(i=0;i<x.length;i++) x[i]+=10;
}

}
  1. 使用Integer.parseInt(Scanner::nextLine())而不是Scanner::nextInt()。查看此以了解更多信息
  2. 为了简单起见,您可以使用boolean变量来跟踪是否需要环回

按如下操作:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] tab = new int[10];
int n;
Scanner inp = new Scanner(System.in);
boolean valid;
do {
valid = true;
try {
System.out.print("Please enter an integer number: ");
n = Integer.parseInt(inp.nextLine());
for (int i = 0; i < tab.length; i++) {
tab[i] = ((int) (Math.random() * 100));
System.out.print(tab[i] + " ");
}
addTen(tab);
System.out.println();
for (int i = 0; i < tab.length; i++) {
System.out.print(tab[i] + " ");
}
} catch (NumberFormatException e) {
System.out.println("The number must be integer");
valid = false;
}
} while (!valid);
}
static void addTen(int[] tab) {
for (int i = 0; i < tab.length; i++) {
tab[i] += 10;
}
}
}

样本运行:

Please enter an integer number: a
The number must be integer
Please enter an integer number: 10.5
The number must be integer
Please enter an integer number: 5
21 50 83 72 95 60 61 64 98 95 
31 60 93 82 105 70 71 74 108 105 

注意,我使用了do...while,它保证循环块内的代码将至少执行一次。在这种特殊情况下,do...while的使用也使代码更易于理解。但是,使用do...while来解决此问题是可选的,如果您愿意,可以继续使用while而不是do...while

使用break;语句。

此语句退出循环,因此将try-catch语句包含在while(True(循环中。如果没有引发错误,则break;语句将退出循环。

Scanner尝试解析输入,直到成功为止。在您的代码中,它总是试图一次又一次地解析第一个非整数输入。为了解决此问题,您可以读取用户输入,而无需尝试将其解析为int。您可以按如下方式更改捕获块:

catch(InputMismatchException e){
final String nonInteger = inp.next();
System.out.println("The number must be integer. You typed: " + nonInteger);
}

最新更新