Boolean在Method中返回True或False

时间:2017-04-20 05:18:54

标签: java arrays for-loop boolean

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

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]




   }
}

3 个答案:

答案 0 :(得分: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 :(得分: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序列并比较它们的长度。

答案 2 :(得分:-1)

public static void 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);
    }
}