布尔理解

Boolean Understanding

我正在努力解决我遇到的一个使用布尔表达式的练习题。我想创建一个程序来说明是否有人应该骑自行车。我有两个变量,想写一个 AND 语句和一个 OR 语句。我的两个变量是路况和温度。

编辑:在收到的帮助下,我取得了一些进步。我从下面 运行 进入第 22 行的另一个问题;

// Program to decide if biking or driving to work is best

import javax.swing.*;

public class SNHU3_4Paper {

public static void main(String[] args) {

    String temperature;
    String roadCondition;

    double temp;
    double weather = 50;
    double road;
    boolean roadIsdry = true;

    temperature = JOptionPane.showInputDialog("Enter temperature outside: ");
    roadCondition = JOptionPane.showInputDialog("Is the road dry (true or false): ");

    temp = Double.parseDouble(temperature);
    road = Double.parseDouble(roadCondition);

    if (temp >= weather && road == roadIsdry)
        JOptionPane.showMessageDialog(null, "Bike to work");

    else {
        JOptionPane.showMessageDialog(null, "Drive to work");

    }

}

}

要将道路状况表示为干燥或潮湿,布尔值就足够了。例如,布尔变量可以这样设置

bool road_is_dry = true;

if(road_is_dry){
  print("The road is dry");
} else {
  print("The road is wet");
}

在这种情况下,道路是干的,所以会打印 "The road is dry"。如果相同的变量设置为 false,则道路不是干燥的(它是潮湿的),因此将打印 "The road is wet"。

这是一个条件语句示例,您可以在其中决定应执行哪个代码块。在设置条件以使用可以放在一起构成简单英语句子的变量名时,In 非常有用。然后可以将基本句子翻译成代码,然后再翻译回来。

如果选择好的变量和函数名称,那么简单的英语句子 "If the road is dry, ride your bike" 可以很容易地翻译成代码,就像这样

if(road_is_dry){
  ride_bike();
}

回答你的第二个问题:I have run into another issue in Line 22 from below

您正在使用 == 比较布尔值 roadIsdry 和字符串 roadCondition。您之前使用 roadCondition 来保存用户的输入然后解析它。

在 Java 中,使用 == 将基本类型(int、boolean、double 等)与对象进行比较几乎不起作用。字符串是对象。 roadIsdry == roadCondition 字面意思是问 Java "Is the memory address of roadCondition the same as the boolean value of roadIsdry?" 并且总是求值为 false,因为这两个东西不一样,甚至没有意义去比较。

您要做的是将 roadIsdry 与布尔值(truefalse 或另一个布尔值变量进行比较。您也可以单独指定 roadIsdryif (...) 期望有一个布尔值作为其最终值来决定要遵循哪个代码分支,因此 if (roadIsdry) 是完全有效的,if (temp >= weather && roadIsdry).

也是如此