学校では、形状の角と座標の数を求める単純なジオメトリ プログラムを作成していました。誤った完全な入力 (つまり、整数ではなく文字) を防ぐために、例外処理を使用することにしました。正常に動作しているように見えますが、間違った入力をすると、エラーがキャッチされ、デフォルト値が設定されます。さらに入力を求め続ける必要がありますが、どういうわけか、これらは新しい入力を求めずに同じ例外をキャッチしてしまいます。
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
try {
int hoeken;
System.out.print("How many corners does your shape have? ");
try {
hoeken = stdin.nextInt();
if(hoeken < 3) throw new InputMismatchException("Invalid side count.");
}
catch(InputMismatchException eVlakken){
System.out.println("Wrong input. Triangle is being created");
hoeken = 3;
}
Veelhoek vh = new Veelhoek(hoeken);
int x = 0, y = 0;
System.out.println("Input the coordinates of your shape.");
for(int i = 0; i < hoeken; i++){
System.out.println("Corner "+(i+1));
try {
System.out.print("X: ");
x = stdin.nextInt();
System.out.print("Y: ");
y = stdin.nextInt();
} catch(InputMismatchException eHoek){
x = 0;
y = 0;
System.out.println("Wrong input. Autoset coordinates to 0, 0");
}
vh.setPunt(i, new Punt(x, y));
}
vh.print();
System.out.println("How may points does your shape needs to be shifted?");
try {
System.out.print("X: ");
x = stdin.nextInt();
System.out.print("Y: ");
y = stdin.nextInt();
} catch(InputMismatchException eShift){
System.out.println("Wrong input. Shape is being shifted by 5 points each direction.");
x = 5;
y = 5;
}
vh.verschuif(x, y);
vh.print();
} catch(Exception e){
System.out.println("Unknown error occurred. "+e.toString());
}
}
したがって、ユーザーが 2 つの側面を持つ形状を作成しようとしたり、整数ではなく char を入力しようとしたりすると、InputMismatchException が生成されて処理されます。次に、コーナーの座標を尋ねてプログラムを続行する必要がありますが、代わりに新しい例外をスローし続け、処理します。
何がうまくいかないのですか?