For school I was creating a simple Geometry program asking for the number of corners and coordinates of a shape. To prevent wrongfull entry (ie chars instead of integers) I figured I'd use exception handling. It seems to work fine, but once I have a wrong input it catches the error and set some default values. It should continue asking for more input, but somehow these end-up catching the same exception without asking for new input.
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());
}
}
Thus if the user starts of by trying to create a shape with 2 sides or inputs a char instead of an integer it produces the InputMismatchException and handles it. It then should continue the program by asking the coordinates of the corners, but instead it keeps throwing new exceptions and handles does.
What is going wrong?