gpt4 book ai didi

java - 创建一个程序,根据一些变量计算出航类价格。想要学习如何减少 if 语句的数量

转载 作者:太空宇宙 更新时间:2023-11-04 12:58:54 25 4
gpt4 key购买 nike

任务是根据以下因素计算客户的航类费用:他们飞往的城市、购买的成人座椅数量和购买的 child 座椅数量。

我仍然是编程初学者,希望找到一种方法来减少必须使用的 if 语句的数量。该程序按原样运行完美,但我认为它很草率。有什么建议么?

    int Johannesburg [] = {780,658}; //flight price for adult and child respectively
int CapeTown [] = {1020,965};
int Bloemfontein [] = {945,835};

int totPrice = 0; // intialization of final price value

String cityChoice = (String)cmbDest.getSelectedItem(); //city that the customer is flying to
int adults = (Integer)jSpinner1.getValue(); //number of adults flying
int kids = (Integer)jSpinner2.getValue(); //number of children flying

if(cityChoice.equals("Johannesburg")){
totPrice = Johannesburg[0]*adults + Johannesburg[1]*kids;
}
if(cityChoice.equals("Cape Town")){
totPrice = CapeTown[0]*adults + CapeTown[1]*kids;
}
if(cityChoice.equals("Bloemfontein")){
totPrice = Bloemfontein[0]*adults + Bloemfontein[1]*kids;
}
jTextArea1.setText("Your booking for " + adults + " adult ticket(s) and " + kids + "children ticket(s) for " + cityChoice + " will cost R" + totPrice); //output statement

最佳答案

如果您使用的是 Java 7 或更高版本,则可以使用 switch 语句。请参阅此处的示例: https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html

关于java - 创建一个程序,根据一些变量计算出航类价格。想要学习如何减少 if 语句的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109838/

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