[英]How to return statement in java method?
我的情况是我无法为我的方法返回语句,因为我的方法无法识别我的返回语句。
public static String j(){
try{
String k ="10";
System.out.println(k);
}
catch (Exception ignore) {}
return k; // error: cannot find symbol
}
错误输出:
cannot find symbol
symbol: variable k
location: class DatabaseSQL
但是,如果我将return语句放在try {}上,它将返回“ missing return statement”
public static String j(){ //missing return statement
try{
String k ="10";
System.out.println(k);
return k;
}
catch (Exception ignore) {}
}
回答
public static String j(){
String k ="10";// put String k before and outside try{}
try{
System.out.println(k);
return k;
}
catch (Exception ignore) {}
}
这是关于变量作用域。 在块内声明的变量仅在该块内可见。 尝试:
public static String j(){
String k = null;
try{
k ="10";
System.out.println(k);
}
catch (Exception ignore) {}
return k;
}
请注意,您绝不应只是默默地吃掉异常。 我知道这只是测试代码的一部分,但是请尽快摆脱这种习惯,从长远来看,您将避免很多痛苦!
在try
块外声明String k
public static String j(){
String k="";
try{
k ="10";
System.out.println(k);
}
catch (Exception ignore) {}
return k;
}
这是因为您在try
块中定义了String k
,因此它将是local variable
,无法在此块外部访问
在第二个代码中,您在try
块中编写了return
语句,并且没有catch
另一个,因此出现了以下错误: "missing return statement"
所以真正的代码需要像这样:
public static String j(){
String k ="10";
try{
System.out.println(k);
}
catch (Exception ignore) {}
return k;
}
如下定义,在第一种情况下,本地变量k
类型的String
的作用域带有try块
public static String j(){
String k ="10";
try{
System.out.println(k);
}
catch (Exception ignore) {}
return k;
}
在第二种情况下,如果捕获到异常,则您不会返回任何内容。 您要么抛出异常,要么有意义地返回一些东西。
问题是因为没有在try and catch之外定义k。 这就是为什么仅当您在try块中返回(如果您还在底部也返回null)的情况下才起作用的原因,它将是它在try块中无法返回的返回值。
改为这样做,它将起作用:
public static String j(){
String k = "";
try{
k ="10";
System.out.println(k);
}
catch (Exception ignore) {}
return k;
}
您需要在方法范围内声明String变量,如下所示:
public static String j(){
String k = "";
try{
k ="10";
System.out.println(k);
} catch (Exception ignore) {}
return k;
}
try{
String k ="10"; // k declare inside the try and it will visible inside try
System.out.println(k);
}
catch (Exception ignore) {}
return k; // error: cannot find symbol // k not visible out side the try
}
你可以这样尝试
String k ="";
try{
k="10";
System.out.println(k);
} catch (Exception ignore) {}
return k;
}
这是因为在return
线的范围内未定义k
。 您可以这样更改:
public static String j(){ //
String k = "10";
try {
System.out.println(k);
} catch (Exception ignore) {}
return k;
}
如果您的字符串分配应在try
块内,请在声明过程中为其提供一些默认值(我建议使用null
),然后在try
块中对其进行重新分配。
在第一次尝试时,return语句中的k
超出了定义范围(在try
块内部)。
第二次尝试时,方法中的并非所有代码路径都返回value 。 最好的选择是在try语句外定义k
并在最后将其返回。
public static String j(){
String k ="10";
try {
System.out.println(k);
}
catch (Exception ignore) {}
return k;
}
根据您的代码,该方法返回String
类型的值。
public static String j(){
您必须确保每个可能的执行路径都知道返回值。 如果一切正常(没有错误的尝试块完成),则返回k
。 但是在失败的情况下(执行catch块),该方法的返回值是不确定的,因为在catch块中或之后没有指定值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.