不确定我在这里做错了什么(布尔标志)

时间:2014-10-10 22:21:38

标签: java

这是我的作业代码片段。我似乎无法让布尔标志正常工作。当我试图找出它时,要么每个名字都得到折扣,要么没有名字得到折扣。澄清迈克或戴安娜应该给予折扣的名称。

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

2 个答案:

答案 0 :(得分: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在对原始问题的评论中所说的那样,最好将整个字符串转换为大写或小写,以减少比较。或者,根据Pshemo的评论,使用equalsIgnoreCase()

您还需要更改:

if (discount = true)

true的值分配给变量discount

if (discount == true)

或根据Pshemo的评论,

if (discount)

答案 1 :(得分:0)

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

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

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

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

然后请记住,折扣是一个布尔变量。所以你不必比较它是否真实。

if (discount) //if will check whether it's true or not if provided with a condition,discount is boolean, so need of comparison
对于布尔运算符,

非常简单。