如何使用 try 块中声明的变量?

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");
}

在上面的代码中,如何在程序中的try块之外访问int变量a

在块内声明的变量(在本例中为 try 块)只能在该范围内访问。如果你想在该范围之外使用它们,你应该声明它们在它之外:

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

最好可能是使用 while-true-loop 并读取整个 String,然后尝试解析它,如果没有失败,则将其分配给变量 a 在循环外声明并尝试块:

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");
    }
}