1
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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 3
    Declare the variable outside the try block and assign it inside – Lino Jul 25 '18 at 16:42
  • 1
    possible duplicate of https://stackoverflow.com/questions/9551020/accessing-variable-inside-try-catch – Santhosh Jul 25 '18 at 16:51
  • Possible duplicate of [Accessing variable inside try catch](https://stackoverflow.com/questions/9551020/accessing-variable-inside-try-catch) – Brian Jul 25 '18 at 17:01

2 Answers2

1

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");
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

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");
    }
}
Lino
  • 19,604
  • 6
  • 47
  • 65