-3

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?

GAlexMES
  • 343
  • 2
  • 19
Dan
  • 17
  • 5

2 Answers2

2

There are many ways this is the simple way, you can use another boolean variable for example :

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n;//no need to initialize n
    boolean b = false;
    while (!b) {//repeat until b = true
        try {
            n = Integer.parseInt(input.nextLine());
            if (n == 0) {
                b = true;//if n == 0 then b = true
            }
        } catch (NumberFormatException e) {
            System.out.println("not int, read again");
        }
    } 

}
YCF_L
  • 49,027
  • 13
  • 75
  • 115
0

You should have used Boolean instead of an integer. Try this.

 package Exceptie;
import java.util.Scanner;

public class Program {   

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int n;
        boolean isInt = false;
        while(!isInt){
            try {
                n=Integer.parseInt(input.nextLine());
                isInt = true;
            }catch(Exception e){
                System.out.println("not int, read again");
            }
        }
    }
}
dranreb dino
  • 250
  • 2
  • 16