gpt4 book ai didi

java - 不确定我在这里做错了什么( boolean 标志)

转载 作者:行者123 更新时间:2023-12-01 22:40:03 25 4
gpt4 key购买 nike

这是我的作业代码片段。我似乎无法让 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com