我正在编写一个简单的applet程序,它从用户那里获取输入并显示它们。 `
EXPSPACE & EXPTIME
` 在paint()方法中为什么必须将str变量声明为null,而在没有初始化的情况下声明另一个字符串变量s1是否正常? 如果没有初始化str变量,IT就不会编译。
答案 0 :(得分:3)
因为你只在保证有值的地方使用s1
的值,但你在一个地方(str
处理程序)使用catch
所在的地方如果你没有将它初始化为某个值,那么> 保证没有值,因为毕竟在分配给try
之前,str
中可能会抛出异常
如果您将g.drawString(str,75,75);
的呼叫移至 try
,则不需要= null
初始值设定项。
旁注:s1
已经是一个字符串,因此无需执行str = String.valueOf(s1)
。只需在s1
行中使用g.drawString(str,75,75);
。
答案 1 :(得分:0)
Java编译器允许未初始化的变量,只要它们在被用于某些东西时保证具有值。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"additionalProperties": true,
"patternProperties": {
"[a-z]": {}
},
"maxProperties": 1,
"minProperties": 1
}
由于上一行已初始化String s1,str = null; // s1 is not set
g.drawString("input in the box",10,50);
try{
s1=text1.getText(); // s1 is set
str=String.valueOf(s1); // s1 is used
}
catch(Exception e){}
g.drawString(str,75,75);
,因此可以安全地将其传递给s1
。
String.valueOf
的问题是它在try-catch块之后使用,它可能会跳过它设置的行。
str
只要在初始化之前有可能使用变量,编译器就会拒绝它。在这种情况下,您可以将String s1,str; // str is not set
g.drawString("input in the box",10,50);
try{
s1=text1.getText(); // if this throws an exception...
str=String.valueOf(s1); // ...this is never reached
}
catch(Exception e){} // the exception is caught and ignored, so we continue
g.drawString(str,75,75); // str is still not set - error!
设置为catch块中的默认值,或者将catch块设置为str
或return
,以便只有throw
行才能到达try块完成无例外。
答案 2 :(得分:0)
实例变量不需要初始化,只需要初始化局部变量(在函数或构造函数内)