2014-10-10 82 views
0

这是我的代码作业的一个片段。我似乎无法让布尔标志正常工作。当我试图弄清楚,要么每个名字都得到折扣,要么没有名字得到折扣。澄清麦克或戴安娜的名字应该给予折扣。不知道我在做什么错在这里(布尔标志)

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."); 
+0

什么问题? – PeterK 2014-10-10 22:24:16

+0

除了字符串比较,你应该用'if(discount == true)'替换'if(discount = true)'。第一种是给变量'折扣'赋值,第二种是比较。 – AntonH 2014-10-10 22:26:50

+0

@SotiriosDelimanolis字符串比较不是唯一的问题 – 2014-10-10 22:27:01

回答

3

首先,为了比较字符串,你不使用==。您需要使用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说,在评论你原来的问题,这将是更好的转换整个字符串到大写或小写,用更少的comparaisons。或者,根据Pshemo的评论,请使用equalsIgnoreCase()

你也需要改变:

if (discount = true) 

这是分配的true给变量discount价值,

if (discount == true) 

,或者按Pshemo的评论,

if (discount) 
+4

我建议避免'如果(折扣== true)',而不是使用'如果(折扣)'。通过这种方式,我们确信我们不会像OP代码一样出错。 – Pshemo 2014-10-10 22:37:14

+3

'equalsIgnoreCase'似乎比手动将字符串转换为大写更好。 – Pshemo 2014-10-10 22:38:47

+0

@Pshemo两个有效点。我编辑了我的答案并将编辑记入您的账户。 – AntonH 2014-10-10 23:08:31

0

我检查了你的代码和我的月食。使用

if(firstName == "mike" || firstName == "diana" || firstName == "Mike" || firstName == "Diana" ||firstName == "MIKE" || firstName == "DIANA") 

是问题所在,因为比较这样的字符串时出现问题。您必须将其更改为

if (firstName.equals("mike")){ 
    discount = true; 
} 

然后请记住,discount是一个布尔变量。所以你不必比较它是否正确。

if (discount) //if will check whether it's true or not if provided with a condition,discount is boolean, so need of comparison 

对于布尔运算符将非常简单。