【发布时间】:2019-11-23 19:30:39
【问题描述】:
我试图让 Java 代码与用户交流。
代码是关于计算披萨价格的,假设披萨价格是最终的 int 并且不会改变。 唯一影响价格的是顾客想要在比萨上添加的东西(番茄、蘑菇、切达干酪)。 我尝试创建涵盖客户使用“if”语句选择的每个选项的代码, 但我认为有更简单的方法可以做到这一点。 (我希望程序仅根据附加名称计算价格。)
例如,客户选择了蘑菇和番茄,因此披萨价格将为披萨价格 + 番茄价格 + 蘑菇价格。
有没有更简单的解决方法? 还是应该用 if/else 语句涵盖客户选择的每个选项?
public static void main(String[] args){
Scanner s= new Scanner(System.in);
final int pizzaPrice= 12;
int Mushrooms = 2;
int Tomato= 2;
int Corn = 2;
int Olives = 2;
int CheddarCheese=3;
int bulgaritCheese=3;
int yellowCheese= 3;
String cheapAddOns ="Mushrooms , Tomato, Corn, Olives";
String expensiveAddOns = "Cheddar cheese , Bulgarit cheese , Yellow cheese";
System.out.println("Please enter first AddOns(Mushrooms , Tomato , Corn, Olives): ");
cheapAddOns=s.next();
System.out.println("Please enter second AddOns (Cheddar cheese , Bulgarit cheese ,Yellow cheese)");
expensiveAddOns=s.next();
if( cheapAddOns== "Mushrooms" || expensiveAddOns=="Cheddar cheese" ) {
System.out.println("Your Pizza price is: $" + pizzaPrice + Mushrooms + CheddarCheese );
}
else if (cheapAddOns=="Tomato" || expensiveAddOns=="Bulgarit cheese") {
System.out.println("Your Pizza price is: $" +pizzaPrice+ Tomato + bulgaritCheese);
}
}
【问题讨论】:
-
用
==比较字符串是行不通的。 -
您可以考虑将您的附加组件及其价格放在地图中。这将简化您的代码。您也可以计算第一个附加组件的价格,然后计算第二个附加组件的价格,然后将它们相加,而不是成对处理。
-
您正在使用“||”什么时候应该使用“&&”。
-
标签: java string if-statement