我对试捕有个小问题。
我的目标是从try块中获取test和test2值,以便以后使用。
怎么处理?
public class MyApplication {
public static void main(String[] args) {
try {
int test = Integer.parseInt("123");
String test2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}
}发布于 2017-07-04 07:10:50
你写道:
....that我可以稍后再用..。
这取决于以后意味着什么,如果您指的是稍后,但采用相同的方法,则执行以下操作:
public static void main(String[] args) {
String test2 = "";
try {
int test = Integer.parseInt("123");
test2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}然后,您可以使用这样的方法
test2.isEmpty()若要检查字符串中的内容是否已更新为ABCD .
如果你指的是以后,但在另一种静态方法中,那就去做。
public class MyApplication {
static String test2 = "";
public static void main(String[] args) {
try {
int test = Integer.parseInt("123");
test2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}
}发布于 2017-07-04 07:10:36
只需在外部范围中声明它们:
public class MyApplication {
public static void main(String[] args) {
int test = Integer.MAX_VALUE; // setting to max value to check if it was set later
String test2 = null;
try {
test = Integer.parseInt("123");
test2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}
}发布于 2017-07-04 07:12:10
正如其他人所指出的,您有作用域问题,这意味着变量Test和Test 2是在try-catch块中声明的。由于这些原因,您不能在try-catch块之外访问这个变量。有几种方法可以克服这一点,最简单的方法是在主函数声明或类声明之后声明。
public class MyApplication {
public static void main(String[] args) {
int TEST = 0;
String TEST2 = "";
try {
TEST = Integer.parseInt("123");
TEST2 = "ABCD";
} catch (NumberFormatException ex) {
System.out.print(ex.getMessage());
}
}
}https://stackoverflow.com/questions/44899171
复制相似问题