間隔

2015-10-10 19 views
0

中的每個數組[i]輸入是ints數組,如果所有ints都是(1; 5>或< 5; 10),則返回true,否則返回false。間隔

public static boolean count(int[] array){ 
     if(10 >= int i : array && int i : array >= 5 || 0 <= int i : array && int i : array <= 5) { 
      return true; 
     }else { 
      return false; 
      break; 
     }} 

預計輸出

array[1,2,3,2,4] - true 
    array[5,7,6,7,8] - true 
    array[1,3,4,7,5] - false 

我知道這種情況的語法是錯誤的,我該怎麼做呢?

+0

閱讀有關循環(你需要一個) – hoijui

回答

0

以下是循環遍歷數組的for循環的語法。如果條件失敗,將立即返回false,否則返回true

public static boolean count(int[] array) { 
for(int i = 0; i<array.length; i++) { 
    if(! <put you condition here>) { 
     return false; 
    } 
} 
return true; 
} 

注:!是否定符號。它與你在if條件下放置的內容相反。

+1

謝謝你,由於某種原因,我認爲這是非常聰明的INT,我使用:數組if條件。 – Oudee

0

這裏有一個辦法做到這一點,我也提高了方法的名稱:

public static boolean allWithin1to5or5to10(int[] array) { 
    return array.length != 0 && (allWithinRange(array, 1, 5) || allWithinRange(array, 5, 10)); 
} 

public static boolean allWithinRange(int[] array, int min, int max) { 
    for (int num : array) { 
     if (!(min <= num && num <= max)) { 
      return false; 
     } 
    } 
    return true; 
} 

它通過這些單元測試:

assertTrue(allWithin1to5or5to10(new int[]{1, 2, 3, 2, 4})); 
assertTrue(allWithin1to5or5to10(new int[]{5, 7, 6, 7, 8})); 
assertFalse(allWithin1to5or5to10(new int[]{1, 3, 4, 7, 5})); 
+0

謝謝,正如我上面回答的那樣,我認爲int i:array會自動創建for循環if條件。而「官方名稱」不算數,我直接在iPad上寫這篇文章,並且只是恰巧是我腦海中浮現的名字 – Oudee

+0

我的意思是你的課外課更加完整,但是因爲我需要的只是有人講述我那個int我:陣列不能被用來創建循環如果條件,我的決定因素是,我已經讀了另一個第一的事實。 – Oudee

0

這另一種方式與int數組檢查。

public static boolean count(int[] array) { 
    for(Integer arr: array){ 
    if(<Your condition>) 
     return true; 
    } 
    return false; 
} 
0

您也可以使用Java 8流了這一點:

boolean oneToFive = IntStream.of(arr).allMatch(i -> (i >= 1 && i <= 5)); 
boolean fiveToTen = IntStream.of(arr).allMatch(i -> (i >= 5 && i <= 10)); 
boolean withinRange = oneToFive || fiveToTen;