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

时间:2018-07-25 16:40:28

标签: java variables exception exception-handling try-catch

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

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

2 个答案:

答案 0 :(得分:1)

在一个块(在这种情况下为try块)中声明的变量只能在该范围内访问。如果您想在该范围之外使用它们,则应声明它们的作用:

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

答案 1 :(得分:0)

最好可能是使用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");
    }
}
相关问题