【发布时间】:2020-10-15 00:21:03
【问题描述】:
我正在尝试编写我的第一个使用布尔值和 if/else 语句的程序。它让用户回答各种问题,并最终告诉他们应该在家吃饭还是在餐馆吃饭。这是通过用户输入“true”或“false”的 Scanner 对象来完成的。它似乎运作良好,但我的问题是,我如何允许用户为“真”输入“是”,为“假”输入“否”,而不是让他们输入这些词?我的作业指定他们应该使用是/否。
import java.util.Scanner;
public class HomeOrRestaurant {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.println("yes/no");
System.out.println("Did you get paid this week?");
boolean paid = scan.nextBoolean();
if (!paid == true){
System.out.println("Eat at home.");
return;
}
else
System.out.println("Did you buy groceries this week?");
boolean boughtGroceries = scan.nextBoolean();
if (boughtGroceries == true){
System.out.println("Eat at home.");
return;
}
else
System.out.println("Do you have leftovers at home?");
boolean leftovers = scan.nextBoolean();
if (!leftovers == true){
System.out.println("Eat at home.");
return;
}
else
System.out.println("Are there enough leftovers for a meal?");
boolean enoughLeftovers = scan.nextBoolean();
if (!enoughLeftovers == true){
System.out.println("Eat at a restaurant.");
}
else
System.out.println("Eat at home.");
}
}
尝试将其中一项设置为“是”或“否”时...
System.out.println("Did you get paid this week?");
boolean paid = scan.nextBoolean();
if (!paid == yes){
System.out.println("Eat at home.");
return;
}
我收到一条错误消息,告诉我找不到符号变量“yes”。作为回应,我尝试创建一个局部变量“是”,但这不起作用。我如何告诉我的程序“是”意味着“真实”?谢谢!
【问题讨论】:
-
顺便说一下,不要比较布尔值;他们已经是布尔值了。直接说
if (!paid)。
标签: java if-statement boolean