如何比较三个布尔值

时间:2013-09-09 12:47:50

标签: java boolean syntax-error

比较三个布尔值并显示第一个为真的。

嘿伙计们,我正在尝试编写一个比较三个布尔值并显示第一个真值的程序。我比较三个单词的长度,它会显示最长的。我得到的错误是我的其他标签不起作用。看看代码。

//Check which word is bigger
    if (len1 > len2)
        word1bt2 = true;

    if (len2 > len3)
        word2bt3 = true;

    if (len1 > len3)
        word1bt3 = true;

    //Check which word is the longest
    if (word1bt2 == true && word1bt3 == true);
        System.out.println(wor1);
        else if (word2bt3 == true);
        System.out.println(wor2);
        else System.out.println(wor3);

我为word1bt2,word2bt3和word1bt3设置了布尔值。在eclipse中,我在上面的代码中得到了一个语法错误。任何帮助都会很棒!

5 个答案:

答案 0 :(得分:3)

if (word1bt2 == true && word1bt3 == true);

错了,你需要删除分号:

if (word1bt2 == true && word1bt3 == true)

else s

相同
else (word2bt3 == true);

也是错的,应该是

else if (word2bt3 == true)

旁注:布尔值可用作条件,因此您的if语句应为

if (word1bt2 && word1bt3) // The same as if (word1bt2 == true && word1bt3 == true)

答案 1 :(得分:2)

  

如何比较三个布尔值?

不要!

如果你发现自己需要比较三个变量,你也可以立即满足任何数量的变量 - 没有任何意义可以随时做好 - 直接做好。

public String longest(Iterator<String> i) {
  // Walk the iterator.
  String longest = i.hasNext() ? i.next() : null;
  while (i.hasNext()) {
    String next = i.next();
    if (next.length() > longest.length()) {
      longest = next;
    }
  }
  return longest;
}

public String longest(Iterable<String> i) {
  // Walk the iterator.
  return longest(i.iterator());
}

public String longest(String... ss) {
  // An array is iterable.
  return longest(ss);
}

答案 2 :(得分:1)

删除;并使用方括号{}进行更改。

if (word1bt2 && word1bt3) {
      System.out.println(wor1);
} else if (word2bt3) {
      System.out.println(wor2);
} else {
      System.out.println(wor3);
}

答案 3 :(得分:0)

使用else块的问题:使用{}的{​​{1}} insteaad附上说明......

首先删除()如果!!!!! - 很常见的错误,结果非常令人费解!

;
  • 如果你在其他分支中需要一个条件,你必须再次使用 - 普通其他人不会有这样的功能......
  • 始终为if语句,循环等的主体使用括号!!!
  • 要非常小心才能使用;在表现不佳的行中:
    • if statements
    • for loops
    • while(){...}循环'while语句

答案 4 :(得分:0)

试试这个,如果长度相等,那么s1被认为是更大的。我还没有添加空检查

 public class Test {
            public static void main(String[] args) {

            String word1 = "hi";
            String word2 = "Hello";
            String word3 = "Hell";
            String Bigger = null;
            if(word1.length() >= word2.length() && word1.length() >= word3.length() ){
                Bigger = word1;
            }else if(word2.length() >= word1.length() && word2.length() >= word3.length()){
                Bigger = word2;
            }else if(word3.length() >= word2.length() && word3.length() >= word1.length()){
                Bigger = word3;
            }
            System.out.println(Bigger);

        }

    }
相关问题