首页 > 解决方案 > 异常java后继续代码

问题描述

我想在索引是已经指定的索引的数组中输入学生数据。所以,我使用 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 来打印输出还是可以在上面添加一些东西?

标签: javaarraysexception

解决方案


你应该颠倒你的顺序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 的答案相同


推荐阅读