having a issue with try and catch, can some one help?
}
having a issue with try and catch, can some one help?
}
。
try-catchが終了した後で実行されます。
したがって、finallyブロックで発生する例外は検出されません。
また、ここでは: try-catchブロックの外部に入力を要求するため、例外をキャッチしません。
解決策の1つは、完全なコード、つまりwhileループの外側にtry-catchブロックを置くことです。
助けてくれてありがとう、私はJavaに新しいので、何をすべきかについてかなり不確かです。私は何を変える必要がありますか? – PeteD
@PeteD 'nextInt()'と 'nextLine()'を呼び出す代わりに、 'nextLine()'だけを呼び出す必要があります。次に、それが単語かどうかをチェックしたり、数値に解析しようとする必要があります( 'Integer.parseInt(...)')。 –
while(true) {
boolean status = true; //represents the status of the process
System.out.print("Enter the number of students that you wish to be part of the module register: ");
int numofstudents = input.nextInt();
try{
if (input.nextLine().equals("exit"))
{System.exit(0);}
status = true;
}catch (InputMismatchException IME){
/*3*/ System.out.println("\nNot a number or an integer!\n");
status = false;
continue;
}
finally{
if (status==false) {
String[] names = new String[numofstudents];
int[] array = new int[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] = input.next();
System.out.print("Enter the student's module: ");
array[i] = input.nextInt();
}
selectionSort(names, array);
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(array));
Scanner scan = new Scanner(System.in);
}
}}
最終的にブロックされても例外ではありません。 finallyブロック内の例外も処理する必要があります.bt私は、boolean値の助けを借りて毎回呼び出されるfinallyブロックを制限しています。これはコード全体を別の方法で置き換える必要があるかもしれない非常に悪いコーディング方法です。
あなたの 'try'ブロックの前に' nextInt() '*を呼び出しています... –
*ヒント:適切な字下げを使ってきれいなコードを書く* – Spidey
Btw、' finally'ブロックは通常は使用されますストリームやコネクションなどを閉じるために、コードの主要部分を持たないようにしてください。また、finallyブロックのコードは、catchの中でcontinueを指定しても実行されます。最終的には成功した試行や失敗したキャッチの後、いくつかの非常に稀な機会(System.exitなど)を除いて。 –