2017-02-09 102 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会发生什么......