作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的作业代码片段。我似乎无法让 boolean 标志正常工作。当我试图弄清楚时,要么每个名字都得到折扣,要么没有名字得到折扣。为了澄清名字迈克或戴安娜应该给予折扣。
String firstName; //user's first name
boolean discount = false; //flag, true if user is eligible for discount
int inches; //size of the pizza
char crustType; //code for type of crust
String crust; //name of crust
double cost = 12.99; //cost of the pizza
final double TAX_RATE = .08; //sales tax rate
double tax; //amount of tax
char choice; //user's choice
String input; //user input
String toppings = "Cheese "; //list of toppings
int numberOfToppings = 0; //number of toppings
//prompt user and get first name
System.out.println("Welcome to Mike and Diane's Pizza");
System.out.print("Enter your first name: ");
firstName = keyboard.nextLine();
if (firstName == "mike" || firstName == "diana" || firstName == "Mike" || firstName == "Diana" ||
firstName == "MIKE" || firstName == "DIANA")
{
discount = true;
}
if (discount = true)
{
cost -= 2.0;
System.out.println ("You are eligible for a $2 discount.");
最佳答案
首先,为了比较字符串,您不使用==
。您需要使用 String#equals()
方法,如 per this SO question .
if (firstName == "mike" || firstName == "diana" || firstName == "Mike" || firstName == "Diana" || firstName == "MIKE" || firstName == "DIANA")
将被替换为
if (firstName.equals("mike") || firstName.equals("diana") || firstName.equals("Mike") || firstName.equals("Diana") || firstName.equals("MIKE") || firstName.equals("DIANA"))
但是,如 Gavin在对原始问题的评论中说,最好将整个字符串转换为大写或小写,以减少比较。或者,按照Pshemo的注释,请使用 equalsIgnoreCase()
。
您还需要更改:
if (discount = true)
即将 true
值赋给变量 discount
,以
if (discount == true)
或者,按照Pshemo的评论,
if (discount)
关于java - 不确定我在这里做错了什么( boolean 标志),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26308895/
我是一名优秀的程序员,十分优秀!