[英]How do i avoid using if-else in this code?
As part of my learning process, I am creating a small program in Java that would help a fictitious company help in selling burgers. 作为学习过程的一部分,我正在用Java创建一个小程序,该程序将帮助虚构的公司帮助销售汉堡。
In the code below, I created class for a burger and added options to add additions to that burger (like lettuce, carrots etc). 在下面的代码中,我为一个汉堡包创建了类,并添加了一些选项以向汉堡包添加其他内容(例如生菜,胡萝卜等)。
The problem I am facing is how to go about checking each extra addition to the base hamburger (base hamburger meaning only bun and meat) without using if-else too much. 我面临的问题是如何在不过多使用if-else的情况下检查基本汉堡包中的每个其他添加物(基本汉堡包仅表示面包和肉类)。 One way I tried (you can also see that in code) is by assigning each addition a number, for example, 1 to lettuce, 2 carrots and so on.
我尝试的一种方法(您也可以在代码中看到)是为每个添加项分配一个数字,例如,生菜1,胡萝卜2等。 By adding 1 and 2 we get 3;
将1和2相加得到3; we can look for 3 to find whether lettuce and carrot are added so that we can calculate price.
我们可以寻找3来查找是否添加了生菜和胡萝卜,以便我们可以计算价格。 I did this with other options too.
我也用其他选择做到了这一点。
Some problems arose, however: 但是,出现了一些问题:
There are some cases when a number generated by adding is created twice from different additions this can be tackled somewhat by multiplying the number with some number or by adding 1 as I create more edge cases. 在某些情况下,由加法生成的数字是由不同的加法创建两次,这可以通过将数字乘以某个数字或在我创建更多边际案例时加1来解决。
My main problem, by creating such cases, is that it would require a lot of if-else statements, which I am trying to avoid in order to effectively code what i need. 通过创建这种情况,我的主要问题是,它将需要很多if-else语句,为了有效地编码所需内容,我试图避免这些语句。
Please suggest if there is any other way to do it. 请建议是否还有其他方法。 Please note code is not yet complete since I didn't want to create more if-else statements (in hamburger class; method cal_price) to check for additions, but it is enough to fully understand the nature of code.
请注意,代码尚未完成,因为我不想创建更多的if-else语句(在汉堡包类;方法cal_price中)来检查添加内容,但这足以完全理解代码的性质。 Code is given below:
代码如下:
public class Main {
public static void main(String[] args) {
Breadroll breadroll_type = new Breadroll("Sesame Seed Bun");
meat meat_type = new meat("Beef");
Hamburger my_burger = new Hamburger("Hamburger",breadroll_type,meat_type);
my_burger.select_items(1,2,3,4);
my_burger.cal_price();
my_burger.getBreadroll_type();
my_burger.getMeat_type();
}
}
public class Breadroll {
private String breadroll_type;
public Breadroll(String breadroll_type) {
this.breadroll_type = breadroll_type;
}
public String getBreadroll_type() {
return breadroll_type;
}
}
public class meat {
private String meat_type;
public meat(String meat_type) {
this.meat_type = meat_type;
}
public String getMeat_type() {
return meat_type;
}
}
public class Hamburger {
private String name;
Breadroll breadroll_type;
meat meat_type;
private double base_price; //Price without addons
private int lettuce;
private int carrot;
private int tomato;
private int cheese;
private int hot_sauce;
private int mustard;
private int total_select;
public Hamburger(String name, Breadroll breadroll_type, meat meat_type) {
this.name = name;
this.breadroll_type = breadroll_type;
this.meat_type = meat_type;
this.base_price = 2.75;
}
public void select_items(int lettuce, int carrot, int tomato, int cheese) {
this.lettuce = lettuce;
this.carrot = carrot;
this.tomato = tomato;
this.cheese = cheese;
this.total_select = lettuce + carrot + tomato + cheese;
}
public void cal_price()
{
double final_price;
double lettuce_price = 0.50;
double carrots_price = 0.60;
double tomatos_price = 0.70;
double cheese_price = 0.85;
if(total_select == 0) {
System.out.println("Order Placed : Hamburger with no additions " + getBase_price() + "$");
}
else if (total_select == 1) {
final_price = getBase_price() + lettuce_price;
System.out.println("Order Placed : Hamburger with all lettuce " + (float) final_price + "$");
}
else if (total_select == 2) {
final_price = getBase_price() + carrots_price;
System.out.println("Order Placed : Hamburger with all carrot " + (float) final_price + "$");
}
else if (total_select == 3) {
final_price = getBase_price() + tomatos_price;
System.out.println("Order Placed : Hamburger with all tomato " + (float) final_price + "$");
}
else if (total_select == 4) {
final_price = getBase_price() +cheese_price;
System.out.println("Order Placed : Hamburger with all cheese " + (float) final_price + "$");
}
else if (total_select*100 == 1000) {
final_price = getBase_price() + lettuce_price + carrots_price + tomatos_price + cheese_price;
System.out.println("Order Placed : Hamburger with all additions " + (float) final_price + "$");
}
}
public String getName() {
return name;
}
public void getBreadroll_type() {
System.out.println(breadroll_type.getBreadroll_type());
}
public void getMeat_type() {
System.out.println(meat_type.getMeat_type());
}
public double getBase_price() {
return base_price;
}
public int getLettuce() {
return lettuce;
}
public int getCarrot() {
return carrot;
}
public int getTomato() {
return tomato;
}
public int getCheese() {
return cheese;
}
}
Your implementation of a 'hamburger' object seems to be a bit over-complicated. 您对“汉堡包”对象的实现似乎有些复杂。 Usually object oriented programming to represent actual, physical objects should choose the simplest, most atomic attributes as possible to avoid situations like this.
通常,面向对象的程序设计代表实际的物理对象,应选择最简单,最原子的属性,以避免出现此类情况。 A hamburger either does or does not have lettuce.
一个汉堡包有或没有生菜。 It either does or does not have tomato.
它有或没有番茄。 My recommendation is to have separate Boolean variables for each topping, or a Boolean array representing the toppings if you'd prefer.
我的建议是为每个浇头使用单独的布尔变量,或者根据需要使用布尔数组表示浇头。 Then, add a get_price() method to your Hamburger which has a single block of if statements for calculating your price.
然后,将get_price()方法添加到您的Hamburger中,该方法只有一个if语句块用于计算价格。 If you really want to get into OOP, each topping could be an object with a price, which you append to a Toppings ArrayList on your hamburger.
如果您真的想加入OOP,则每个浇头都可以是一个带有价格的对象,您可以将该价格附加到汉堡包的Toppings ArrayList上。 Then, your get_price() method would use a for-each to total all the prices of your Topping objects, as well as your hamburger's price attribute.
然后,您的get_price()方法将使用for-each来总计Topping对象的所有价格以及汉堡包的price属性。 This method might be better if you want multiple quantities of the same topping.
如果您想要多个相同的浇头,则此方法可能更好。 This is the fun part of programming - you can choose the implementation that makes the most sense to you and try it out!
这是编程中最有趣的部分-您可以选择最适合自己的实现,然后尝试一下!
Made a hamburger with name, breadtype, meattype and added the extra's later on, you can make seperate methods for the breadtype and meat as well. 用名称,面包类型,肉类型制作一个汉堡包,并在以后添加额外的汉堡包,您也可以对面包类型和肉类使用不同的方法。 In the extra methods we calculate the extra price beforehand so calling getPrice() sums up all the extras with chosen bread/meat type.
在extra方法中,我们预先计算了多余的价格,因此调用getPrice()可以将所选的面包/肉类类型的所有多余的东西相加。 There are other ways to do this but this way you'll also have an example of a contract and switch statement.
还有其他方法可以执行此操作,但是通过这种方法,您还将获得合同和转换语句的示例。 Removed a few ingredients but you get the point.
删除了一些成分,但您明白了。
Also take look at the naming conventions how they are different from yours. 还请查看命名约定,它们与您的约定有何不同。
class HamburgerContract {
// Specify your constants in this class so all classes are able to communicate with the same values
// Change the name to something shorter like HBC for easier reference, ie HBC.BR_TYPE_SESAM
public static final int BR_TYPE_SESAM = 1;
public static final int BR_TYPE_HONEY = 2;
public static final int MEAT_TYPE_COW = 1;
public static final int MEAT_TYPE_CHICKEN = 2;
}
public class Hamburger {
public static void main(String[] args) {
// Made a hamburger with name, breadtype, meattype and added the extra's later on
// You can make seperate methods for the breadtype and meat as well
// In the extra methods we calculate the extra price beforehand
// So calling getPrice() sums up all the extras with chosen bread/meat type
// There are other ways to do this but this way you'll also have an example of a contract and switch statement
// Removed a few ingredients but you get the point
Hamburger myHamburger = new Hamburger("Varadero Burger", HamburgerContract.BR_TYPE_SESAM, HamburgerContract.MEAT_TYPE_CHICKEN, 2.50);
myHamburger.addCarrot();
myHamburger.addLettuce();
myHamburger.removeCarrot();
System.out.print("The price of your " + myHamburger.getName() + "is $ " + myHamburger.getPrice());
}
private String burgerName;
private int breadrollType;
private int meatType;
private boolean lettuce;
private boolean carrot;
private double basePrice;
private double extraPrice;
public Hamburger(String burgerName, int breadrollType, int meatType, double basePrice) {
this.burgerName = burgerName;
this.breadrollType = breadrollType;
this.meatType = meatType;
this.basePrice = basePrice;
this.extraPrice = 0;
this.lettuce = false;
this.carrot = false;
}
public void addLettuce() {
// extra check if lettuce is not already added, so you wont add to the price twice
// same goes for removing the lettuce or the carrot methods
if (!lettuce) {
letuce = true;
extraPrice += 0.25;
}
}
public removeLettuce() {
if (lettuce) {
letuce = false;
extraPrice -= 0.25;
}
}
public void addCarrot() {
if (!carrot) {
carrot = true;
extraPrice += 0.20;
}
}
public void removeCarrot() {
if (carrot) {
carrot = false;
extraPrice -= 0.20;
}
}
public String getName() {
return burgerName;
}
public double getPrice() {
switch (breadrollType) {
case HamburgerContract.BR_TYPE_HONEY: extraPrice += 0.25; break;
case HamburgerContract.BR_TYPE_SESAM: extraPrice += 0.50; break;
}
switch (meatType) {
case HamburgerContract.MEAT_TYPE_COW: extraPrice += 0; break;
case HamburgerContract.MEAT_TYPE_CHICKEN: extraPrice += 0.50; break;
}
return basePrice + extraPrice;
}
}
You don't need to use conditional statements at all, just multiply the price of each item by its price: 您根本不需要使用条件语句,只需将每个项目的价格乘以其价格即可:
final_price = getBase_price()
+ lettuce_num * lettuce_price
+ carrots_num * carrots_price
+ tomatos_num * tomatos_price
+ cheese_num * cheese_price;
In your set method you should then set the number/amount of items (eg, lettuce) and not 1 == lettuce and 2 == xxx : 然后,在您设置的方法中,您应该设置项目的数量/数量(例如生菜),而不是1 ==生菜和2 == xxx:
my_burger.select_items(5,0,0,0); // 5 lettuce, 0 all other
my_burger.select_items(1,0,0,90); // 1 lettuce, 90 cheese, 0 all other
Putting it all together (minified): 放在一起(最小化):
public class Main {
public static void main(String[] args) {
Hamburger my_burger = new Hamburger("Hamburger");
my_burger.select_items(
100, // 100 lettuce
0, // 0 carrot
2, // 2 tomato
1); // 1 cheese
my_burger.cal_price();
}
}
public class Hamburger {
private String name;
private double base_price = 2.75;
private int lettuce;
private double lettuce_price = 0.50;
private int carrot;
private double carrots_price = 0.60;
private int tomato;
private double tomatos_price = 0.70;
private int cheese;
private double cheese_price = 0.85;
public Hamburger(String name) {
this.name = name;
}
public void select_items(int lettuce, int carrot, int tomato, int cheese) {
this.lettuce = lettuce;
this.carrot = carrot;
this.tomato = tomato;
this.cheese = cheese;
}
public void cal_price()
{
double final_price = getBase_price()
+ lettuce * lettuce_price
+ carrots * carrots_price
+ tomato * tomatos_price
+ cheese * cheese_price;
// TODO print price
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.