-2

こんにちは、私は学校のプロジェクトに取り組んでおり、すべてのメソッドで return ステートメントが欠落しているとプログラムが言い続ける理由を理解するのに非常に苦労しています。

これが私のコードです:

public class Temperature {
 private int temperature;

 //constructors
 public int Test( int temperature )
 {
    temperature = temperature;
    return temperature;
 }
 public int TempClass()
 {
    temperature = 0;
    return 0;
 }



 // get and set methods
 public int getTemp()
 {
    return temperature;
 }

 public void setTemp(int temp)
 {
    temperature = temp;
 }

 //methods to determine if the substances
 // will freeze or boil
 public static boolean isEthylFreezing(int temp)
 {
    int EthylF = -173;

    if (EthylF <= temp)
    {System.out.print("Ethyl will freeze at that temperature");}
    else 
    return false;
 }

 public boolean  isEthylBoiling(int temp)
 {
    int EthylB = 172;

    if (EthylB >= temp)
    System.out.print("Ethyl will boil at that temperature");
    else
    return false;
 }

 public boolean  isOxygenFreezing(int temp)
 {
    int OxyF = -362;

    if (OxyF <= temp)
    System.out.print("Oxygen will freeze at that temperature");
    else
    return false;
 }

 public boolean  isOxygenBoiling(int temp)
 {
    int OxyB = -306;

    if (OxyB >= temp)
    System.out.print("Oxygen will boil at that temperature");
    else
    return false;
 }

 public boolean  isWaterFreezing(int temp)
 {
    int H2OF = 32;

    if (H2OF <= temp)
    System.out.print("Water will freeze at that temperature");
    else
    return false;
 }

 public boolean  isWaterBoiling(int temp)
 {
    int H2OB = 212;

    if (H2OB >= temp)
    System.out.print("Water will boil at that temperature");
    else
    return false;
 }
}
4

3 に答える 3

4

問題の行は次のとおりです。

if (EthylF <= temp)
{System.out.print("Ethyl will freeze at that temperature");}
else 
return false;

return falseコンパイラはそれが分岐に属すると考えるelseため、EthylF <= temp分岐が発生した場合、メソッドは値を返さずに終了します。残りのbooleanゲッターについても同様です。

適切にインデントして中括弧を使用すると、次のような問題を回避するのに役立ちます。次のようにフォーマットされた同じコードが表示された場合

if (EthylF <= temp) { 
    System.out.print("Ethyl will freeze at that temperature");
} else { 
    return false;
}

問題がどこにあるかが正確にわかります。

ブランチに追加するreturn trueと、この問題は解決します。if

于 2013-11-03T20:56:28.967 に答える
1
int EthylF = -173;

if (EthylF <= temp)
{System.out.print("Ethyl will freeze at that temperature");}
else 
return false;

このメソッドは、 の場合にのみ (false) を返しますEthylF > temp。それ以外の場合、print はありますが、return ステートメントはありません。

非 void メソッド内で可能なすべてreturnの実行パスは、ステートメントまたはステートメントで終了する必要がありthrowます。

于 2013-11-03T20:57:13.287 に答える