2014-10-10 83 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 

對於布爾運算符將非常簡單。