![](/img/trans.png)
[英]Passing boolean argument in method but method boolean variable is still unused
[英]boolean method with array argument
我花了很長時間才能弄清楚這些問題,但是我被困在這里。 我需要編寫一個布爾方法,該方法將數組作為參數,如果數組中的數字降序,則應返回true。 卜,只要我嘗試我有相同的值或錯誤。 這是我的代碼:
public class Question1c{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
int first = numbers[0];
for (int i : numbers){
if(first <= i){
first = i;
return true;
}
//else{
// return false;
//}
}return false;
}
}
您的代碼中的問題是,直到遍歷整個數組之后,您才能返回true
。 但是,一旦檢測到“倒置”,即可能出現false
,即跟在您之前看到的數字之后的數字大於前一個數字的情況。
您合理地接近可行的解決方案-您需要刪除return true
,取消注釋else
,然后將最終return false
更改為return true
。
為了使代碼更具可讀性,請first
將其重命名為prior
。 還可以考慮將for
循環的“ foreach”版本更改for
跳過數組初始元素的常規for
循環。 這樣,您就可以檢測到當前檢測到的遞減順序,而不是不遞增的順序。
不確定我是否了解,但這不能解決您的問題嗎?
public class Question1c{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
for (int i = 0; i < numbers.Length; i++){
if (i == 0)
continue;
if (numbers[i - 1] >= numbers[i])
return false;
}
return true;
}
}
您實質上只是在檢查數組中的前一項是否大於或等於數組中的當前項,不是嗎?
首先使用numbers[0]
初始化,這會導致幾個問題:
IndexOutOfBoundsException
numbers[0] <= numbers[0]
) 您最好檢查numbers
的長度是否為0,並使用“正常”循環(使用索引)。
您的返回值也應該是負數。
這可能會解決您的問題。
public class Question{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
int first = numbers[0];
for (int i = 1; i < numbers.length ; i++) {
if (first <= numbers[i]) {
return false;
}
first = numbers[i];
}
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.