异常java后继续编码

时间:2018-04-30 12:37:15

标签: java arrays exception

我想在数组中输入学生数据,其中索引是已指定的索引。因此,我使用try,catch和loop来输入学生,但是当用户输入的数据多于索引时,我希望程序让它们停止输入但结果将被打印。例如:

import java.util.Scanner;

String[] students = new String[5];
String answer = "";
try {
    do {
        //my code to input the students
    }
    while(answer.equalsIgnoreCase("Y"))
    //output the students
}
catch(ArrayIndexOutOfBoundsException ex)
{
    //the code that let the code continue or print the data from above
}

我应该使用finally来打印输出还是可以在上面添加一些内容?

2 个答案:

答案 0 :(得分:0)

首先在运行循环之前,您应该始终检查array length。 更好的方法:

String[] students = new String[5];
String answer = "";

for (int i = 0; i < students.length; i++) {
    // my code to input the students
}
//output the students

无论如何你仍然想要这样做(我假设你必须使用do-while循环和异常处理)

您可以try - catch - 然后 - break ArrayIndexOutOfBoundsException循环中的while,如下所示,然后在catch块中打印出学生

String[] students = new String[5];
String answer = "";

do {
 try {
  //my code to input the students
 } catch (ArrayIndexOutOfBoundsException ex) {
  //the code that let the code continue or print the data from above
   break;
 }
}
while (answer.equalsIgnoreCase("Y"))
//output the students
}

答案 1 :(得分:0)

您应该颠倒try catchloop

的顺序
import java.util.Scanner;

String[] students = new String[5];
String answer = "";
do {
  try {
    //my code to input the students
  } catch(ArrayIndexOutOfBoundsException ex)
  {
    //the code that let the code continue or print the data from above
  }
}
while(answer.equalsIgnoreCase("Y"))
//output the students
编辑:这与Shanu Gupta的答案相同