2017-09-26 26 views
-1

我對這項任務沒有盡頭。看着它,我覺得括號和if else語句都是很好的。但是,錯誤說 「缺少return語句}」
_____________________________________________________________________^If Else If。在正確地形成退貨時遇到問題

public class CompareNums { 
    // TODO - write your code below this comment. 
    // The method you define will return one of three possible strings: 
    // - "less than": if the first parameter is less than the second 
    // - "equal to": if the first parameter is equal to the second 
    // - "greater than": if the first parameter is greater than the second 
    // Make sure you return _exactly_ the above strings 
    public static String comparison(int first, int second) { 
     if (first<second) { 
      return "less than"; 
     } else if (first==second) { 
      return "equal to"; 
     } else if (first>second) { 
      return "greater than"; 
     } 
    } 



    // DO NOT MODIFY main! 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter first integer: "); 
     int first = input.nextInt(); 
     System.out.print("Enter second integer: "); 
     int second = input.nextInt(); 
     System.out.println("The first integer is " + 
          comparison(first, second) + 
          " the second integer."); 
    } 
} 

回答

0
if (first<second) { 
      return "less than"; 
     } else if (first==second) { 
      return "equal to"; 
     } else if (first>second) { 
      return "greater than"; 
     } 

最後else if是多餘的,是問題的真正原因。自然,如果在上述2個條件是假,則first將比second更大。只是使用else代替else if

if (first<second) { 
      return "less than"; 
     } else if (first==second) { 
      return "equal to"; 
     } else { 
      return "greater than"; 
     } 
1

你需要結束if報表與else,如果你使用的是函數內部回報。錯誤基本上是說如果沒有滿足這些條件,仍然需要返回。使用您例如,你可以說這個:

public static String comparison(int first, int second) { 
     if (first<second) { 
      return "less than"; 
     } else if (first>second) { 
      return "greater than"; 
     } else { 
      return "equal to"; 
     } 
    } 

你可以假設,如果第一比第二不小於或大於它因此等於。