I'm new to Java and I want to make a program that reads an int from keyboard. If you enter a non-int value, it throws an exception and reads again until you enter an int. The code is:
package Exceptie;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=0;
while(n==0){
try {
n=Integer.parseInt(input.nextLine());
if (n==0) break;
}catch(Exception e){
System.out.println("not int, read again");
}
}
}
}
Can you suggest an approach that doesn't require n to be initialized?