java异常后继续代码
我想在数组中输入students数据,该数组的索引是已经指定的索引。因此,我使用try、catch和loop输入学生,但当用户输入的数据超过索引时,我希望程序使他们停止输入,但结果将被打印出来。例如:java异常后继续代码,java,arrays,exception,Java,Arrays,Exception,我想在数组中输入students数据,该数组的索引是已经指定的索引。因此,我使用try、catch和loop输入学生,但当用户输入的数据超过索引时,我希望程序使他们停止输入,但结果将被打印出来。例如: import java.util.Scanner; String[] students = new String[5]; String answer = ""; try { do { //my code to input the students } wh
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打印输出,还是可以在上面添加一些内容?首先在运行循环之前,您应该始终检查
数组
长度
。
更好的方法是:
String[] students = new String[5];
String answer = "";
for (int i = 0; i < students.length; i++) {
// my code to input the students
}
//output the students
您应该颠倒
try catch
和循环的顺序:
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的答案相同我认为你的try catch
应该在循环中。您将能够添加内容,如果发生异常,您将只丢失上次输入的值。正如您在这里编写的代码所示,如果出现任何异常,一切都将丢失。您不应该等待异常,这是糟糕的编程。相反,在你的循环中加入数组.length
,这让我想起了一个故事,一个推销员从一栋楼上摔下来,他正在演示他的窗户是如何抵抗的,你可以在不打破它的情况下撞上它。。。他死了。即使存在失败的保险柜(异常),也要防止这种情况发生。否则,坏事就会发生。
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