这段代码有什么问题。在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;
}
}
答案 0 :(得分:2)
因为您在此处定义了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;
}
}
答案 1 :(得分:0)
if(dataRight==false)
{
System.out.printf("\nAs wrong data, calculation Not possible.\n ");
// should return from here as well or throw exception
}
答案 2 :(得分:0)
错误发生在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;
}
答案 3 :(得分:0)
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;
}
答案 4 :(得分:0)
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());
}
}