gpt4 book ai didi

java - 如何使用try block 中声明的变量?

转载 作者:行者123 更新时间:2023-11-30 06:04:58 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于java - 如何使用try block 中声明的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51523882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com