既然我已经在if/else中使用了return语句,那么我应该把什么作为我的方法的返回语句呢?
public static boolean rowsAreValid(int[][] array){
for (int i = 0; i < array.length; i++){
for (int k = i +1; k < array.length; k++){
for (int j = 0; j < array[i].length; j++) {
// Returns false if the numbers are not the same
if (array[i][j] == array[k][j]){
System.out.println("false");
return false;
}
//Returns true if numbers are the same
else {
System.out.println("true");
return true;
}
}
}
}
// RETURN STATEMENT
}发布于 2015-09-23 11:32:00
这段代码令人困惑,但在编译器抱怨的层面上(没有解决代码的整体结构):您可能会遇到循环不执行的情况,如果发生这种情况,您的if-else块将永远不会执行,您也不会返回。例如,如果是array.length == 0,就会发生这种情况。在这些情况下,您需要确定此方法的正确答案是什么,并提供相应的返回。
发布于 2015-09-23 11:44:27
由于您希望在数字相同时返回true,因此在返回语句中放入:return true。因为通过推理,你的数字永远不会不一样。
另外,正如@blm在评论中提到的,我认为您代码中的代码片段:
// Returns false if the numbers are not the same
if (array[i][j] == array[k][j]){
...
}应该是,
// Returns false if the numbers are not the same
if (array[i][j] != array[k][j]){
...
}否则,你的逻辑就不正确了。
https://stackoverflow.com/questions/32730390
复制相似问题