2017-02-09 103 views
1

我想檢查兩個數組是否具有相同的元素,但它說缺少返回語句,雖然我已經返回如下。有什麼問題? 如果我在void函數中寫入,我的方法可以得到正確的值。因爲它是可能的而沒有返回任何東西到了最後布爾類缺少返回語句java

public static boolean get(int[] One, int[] Two, int target) { 
    int [] temp = new int[One.length]; 
    for (int i = 0 ; i < One.length; i ++){ 
     temp[i] = target - One[i]; 
    } 

    for (int m = 0; m < temp.length; m++){ 
     for (int n = 0; n < Two.length; n ++){ 
      if (temp[m]==Two[n]){ 
       return true; 
      } 
      else return false; 
     } 

    } 

}

+0

你的代碼是不是真的,我已經回答了它如何刪除這個錯誤,但我認爲你的代碼是不正確的... –

回答

1

編譯器不會接受它。你可以像這樣構造它,這樣無論輸入是什麼,它總是會返回true或false。

public static boolean get(int[] One, int[] Two, int target) { 
    int [] temp = new int[One.length]; 

    for (int i = 0 ; i < One.length; i ++){ 
     temp[i] = target - One[i]; 
    } 

    for (int m = 0; m < temp.length; m++){ 
     for (int n = 0; n < Two.length; n ++){ 
      if (temp[m]==Two[n]){ 
       return true; 
      } 
      else { 
       return false; 
      } 
     } 
    } 

    return false; 
} 
+0

它是沒有效率,嘗試'返回true' for循環 –

+0

你是新來的stackoverflow,看看操作,它在'else'中返回'false'添加它,我不會downvote你的解決方案,糾正它,我會upvote它:) –

+0

哎呀,謝謝我錯過了 – jarthur

0

這是可能的功能,而無需返回如果任temp.length或Two.length爲0

0

我不知道你該怎麼辦,但完成如果添加一個return false;到最後你的方法的路線,它會工作

public static boolean get(int[] One, int[] Two, int target) { 
    int [] temp = new int[One.length]; 
    for (int i = 0 ; i < One.length; i ++) 
     temp[i] = target - One[i]; 

    for (int m = 0; m < temp.length; m++){ 
     for (int n = 0; n < Two.length; n ++){ 
      if (temp[m]==Two[n]) return true; 
      else return false; 
     } 
    } 
    return false; 
} 
0

想想如果temp.length0會發生什麼......