Alasyam Aravind
Alasyam Aravind

Reputation: 17

how to use the variables declared in try block?

Scanner sc=new Scanner(System.in);
try {
    int a=sc.nextInt();
}
catch (Exception e) {
    System.out.println("enter integer only");
}

in the above code, how to access the int variable a outside of the try block in the program?

Upvotes: 1

Views: 2860

Answers (2)

Lino
Lino

Reputation: 19926

Best would probably be to use a while-true-loop and read a whole String, and then try to parse that, and if it doesn't fail assign it to the variable a declared outside of the loop and try block:

Scanner sc = new Scanner(System.in);
int a;
while(true){
    String potentialInt = sc.nextLine();
    try{
        a = Integer.parseInt(potentialInt);
    } catch(NumberFormatException nfe){
        System.out.println("Enter integers only");
    }
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311498

Variables declared inside a block (a try block in this case) are only accessible within that scope. If you want to use them outside that scope, you should declare them outsie of it:

int a; // Declared outside the scope
try {
    a=sc.nextInt();
}
catch (Exception e){
    System.out.println("enter integer only");
}

Upvotes: 1

Related Questions