在java中编写布尔语句

时间:2017-07-24 04:55:44

标签: java eclipse

我正在做一个要求的练习:

"如果一个人年龄介于10到20岁之间,他们可享受50%的折扣"

为什么我的布尔语句失败?

package exercises;

import java.util.Scanner;

public class FareDiscountApp {

    public static void main(String[] args) {
        PersonClass discountPerson;

        discountPerson = new PersonClass();

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter the peron's age: ");
        discountPerson.age = keyboard.nextInt();
        System.out.println("Please enter the peron's weight:");
        discountPerson.weight = keyboard.nextDouble();
        System.out.println("Is the person a student (true/false:");
        discountPerson.student = keyboard.nextBoolean();
        System.out.println("Please enter the peron's gender (M/F");
        discountPerson.gender = keyboard.next().charAt(0);

        if (discountPerson.age > 65)
        {
            System.out.println("This peron's bus discount is 100%");
        }
        else if ((discountPerson.student == !(false)) && (discountPerson.age > 10 && < 20))
        {


    }

}

3 个答案:

答案 0 :(得分:2)

试试这个

else if (discountPerson.student && discountPerson.age > 10 && discountPerson.age < 20)

因为您遗漏了与20

的比较

注意我是如何简化第一次比较并摆脱不必要的括号

答案 1 :(得分:2)

没有必要比较布尔值,请在此处查看您的表达式评估的内容:

discountPerson.student == !(false)
=> discountPerson.student == true
=> true == true
=> true

相反,你可以写:

if (discountPerson.student && (discountPerson.age > 10 && discountPerson.age < 20) {
    //...
}

答案 2 :(得分:1)

那必须是:

if (discountPerson.student && discountPerson.age > 10 && discountPerson.age < 20) {

    // ...
}