2017-04-20 459 views
-3

无法弄清楚如何编写我的方法,我尝试的任何操作都会给我编译错误。总之,我需要我的方法遍历我传递下来的布尔数组。了解False是否连续出现,或者True是否连续出现。在我提供的False数组中出现了更多的连续性,因此它应该将false返回给main。我现在完全失去了任何提示?Boolean在方法中返回True或False

public class booleanTF 
{ 
    public static void main(String [] args) 
    { 
     boolean[] guess = {false,true,false,false,false,true,true}; 




    } 
    public static boolean longerTF(boolean[] guess) 
    { 

    int variable = 0; 

    for(int x = 0; x < guess.length; x++) 
    { 
    if(guess[x] 




    } 
} 
+0

请参考[游览],学习http://stackoverflow.com/help/how-to-ask并制作[mcve]。 – Yunnosch

+2

可能[复制](http://stackoverflow.com/questions/43509871/boolean-array-passed-to-method-to-return-true-or-false) –

+0

所以你不会包括编译错误? – John3136

回答

0

您可以使用标志来检查当前元素是true还是false,以及数组的前一个元素是什么。 您可以尝试以下方法。问我,如果您有任何疑问

public class booleanTF { 
public static void main(String[] args) { 
    boolean[] guess = { false, true, false, false, false, true, true }; 

    boolean result = longerTF(guess); 
    System.out.println(result); 
} 

public static boolean longerTF(boolean[] guess) { 

    int variable = 0; 
    boolean trueFlag = false; 
    boolean falseFlag = false; 
    int trueCount = 0, falseCount = 0; 
    for (int x = 0; x < guess.length; x++) { 
     if (guess[x] == true) { 
      if (falseFlag == true) { 
       trueCount = 0; 
      } 
      trueFlag = true; 
      falseFlag=false; 
      trueCount++; 
     } else { 
      if (trueFlag == true) { 
       falseCount = 0; 
      } 
      falseFlag = true; 
      trueFlag=false; 
      falseCount++; 
     } 
    } 
    if (trueCount > falseCount) { 
     return true; 
    } else { 
     return false; 
     } 
    } 
    } 
-1

公共静态无效booleanTF(){

boolean[] arr = {true,true,false,false,false}; 
    int fIndex = 0; 
    int fMaxCount = 0; 
    int tIndex = 0; 
    int tMaxCount = 0; 
    for(boolean ar : arr){ 
     if(ar){ 
      tIndex++; 
      if(tIndex > tMaxCount){ 
       tMaxCount = tIndex; 
      } 
      fIndex= 0; 

     }else{ 
      fIndex++; 
      if(fIndex > fMaxCount){ 
       fMaxCount = fIndex; 
      } 
      tIndex=0; 
     } 
    } 
    if(fMaxCount > tMaxCount){ 
     System.out.println("False appers more " + fMaxCount); 
    }else if (tMaxCount > fMaxCount){ 
     System.out.println("True appers more " + tMaxCount); 
    }else{ 
     System.out.println("Same Count " + tMaxCount); 
    } 
} 
0

显然没有做到这一点的最有效的方法,但是:

public static boolean longerTF(boolean[] guess) { 
    return findMaxSeqLength(guess, true) > findMaxSeqLength(guess, false); 
} 

private static int findMaxSeqLength(boolean[] array, boolean value) { 
    int maxSeqLength = 0; 
    int counter = 0; 

    for (boolean b : array) { 
     counter = (b == value) ? ++counter : 0; 
     maxSeqLength = Math.max(maxSeqLength, counter); 
    } 

    return maxSeqLength; 
} 

查找最长true序列,找到最长的false序列并比较它们的长度。

相关问题