Java 从Try Catch中获取字符串
我对试抓有点意见 我的目标是从try块中获取Java 从Try Catch中获取字符串,java,string,scope,Java,String,Scope,我对试抓有点意见 我的目标是从try块中获取test和test2值,以便以后使用 如何处理 public class MyApplication { public static void main(String[] args) { try { int test = Integer.parseInt("123"); String test2 = "ABCD"; } catch (NumberFormatExce
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());
}
}
}
只需在外部范围中声明它们:
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());
}
}
}
你写道:
…我以后可以用它
这取决于“晚”的含义,如果您是指“晚”,但使用相同的方法,请执行以下操作:
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());
}
}
}
正如其他人所指出的,您存在范围问题,这意味着您的变量Test和test2是在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());
}
}
}
您有范围问题,将声明移出try.declare在另一个范围中,例如class@terades:请使用驼峰大小写作为变量名。大写的所有内容都是为最终变量/常量保留的。我的建议是将声明从Suresh Atta提到的try中移出,并在最终块中指定最终值。希望你知道我们为什么要用试捕拦网谢谢你,先生!:)我想我现在明白了。。当我首先声明TEST和TEST2时,try函数将它们的值设置为“xxx”并结束,然后我可以稍后使用这些值,或者?:)将TEST初始化为
Integer.MAX_value
,这样您就可以检查它是否已被设置。如果它被初始化为0,则无法判断它是默认值还是刚刚设置的值(不适用于123!=0的特定情况)。@terades Exaclty。你可以像StephaneM说的那样初始化它谢谢你解释得很好!谢谢,我试试看:)嘿!我看了你对这个问题的编辑。请下次也删除“谢谢”+我会的