[英]method returning value in Java
这段代码有什么问题? 在Eclipse中,为什么显示该方法必须返回一个double值?
public void setLength(double length){
if(length>0.0 && length<20.00){
this.length=length;
}else{
dataRight=false;
throw new IllegalArgumentException( "Length is not correct." );
}
}
public double getLength(){
if(dataRight==false){
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
}else{
return length;
}
}
因为您在此处定义了double
类型的结果值:
public double getLength()
{
if(dataRight==false)
{
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
}
else
{
return length;
}
}
但在您的第一个if condition
您什么也不返回。
返回第一个condition
至少一个默认值,或者如果绝对无效则抛出exception
。
if(dataRight==false)
{
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
return -1;
}
要么
public double getLength() throws Exception
{
if(dataRight==false)
{
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
throw new Exception("wrong data, calculation Not possible.");
}
else
{
return length;
}
}
if(dataRight==false)
{
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
// should return from here as well or throw exception
}
错误发生在getLenght()方法中。
如果if语句中的条件为true,则不返回任何内容。 否则,您将返回一个双精度值。
因此,Java编译器(不是Eclipse)期望返回一个double。
您可能想要类似
public double getLength() {
if( dataRight == false )
throw new RuntimeException("\nAs wrong data, calculation Not possible.\n ");
return this.length;
}
public double getLength()
{
if(dataRight==false)
{
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
return 0.0; //<-- Return path must exist for all possible paths in a method, you could also add exception handling
}
else
return length;
}
public class Test {
private double length;
private boolean dataRight = true;
public void setLength(double length) {
if (length > 0.0 && length < 20.00) {
this.length = length;
} else {
dataRight = false;
throw new IllegalArgumentException("Length is not correct.");
}
}
public double getLength() {
if (!dataRight) {
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
return 0.0; // <<<--- If dataRight is false then return double
// default values
}
return length;
}
public static void main(String[] args) {
Test test= new Test();
test.setLength(24);
System.out.println(test.getLength());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.