简体   繁体   English

在 Java 中编写许多 if 语句的更好方法?

[英]Better way to write many if statements in Java?

So I have this homework where I need to build a vending machine, and I assigned a coordinate to every product (A1, A2, A3..) and when the user enters the coin value I have to calculate if he can buy the product that he chose and if yes calculate the change, since i'm still new to programming I now have ended up with many statements like this所以我有这个作业,我需要建造一个自动售货机,我为每个产品(A1,A2,A3 ..)分配了一个坐标,当用户输入硬币价值时,我必须计算他是否可以购买该产品他选择了,如果是的话,计算变化,因为我还是编程的新手,我现在已经结束了很多这样的陈述

if ("a1".equals(choice)) {
    System.out.println("You chose SNICKERS!");
    if (money < 50) {
        System.out.println("This is not enough money to buy this product");
    } else if (money >= 50) {
        System.out.println(" Price = 50  Your change = " + (money - 50));
    }
}

where the only things changing are the coordinates (a1, a2, a3, a4, b1, b2 and so on) and the prices.唯一发生变化的是坐标(a1、a2、a3、a4、b1、b2 等)和价格。 What would be a better way to do this?什么是更好的方法来做到这一点?

You could use a more OO approach.您可以使用更面向对象的方法。

Make a class called Product :创建一个名为Product的类:

class Product {
    private String name;
    private int price;

    public String getName() { return name; }
    public int getPrice() { return price; }

    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

Then, create a HashMap<String, Product> and add all your products and their coordinates in:然后,创建一个HashMap<String, Product>并将所有产品及其坐标添加到:

HashMap<String, Product> productMap = new HashMap<>();
productMap.put("A1", new Product("Snickers", 50));
productMap.put("A2", new Product("Something else", 40));
// do this for every coordinate...

Now, you can just use this code:现在,您可以使用以下代码:

Product chosenProduct = productMap.get(choice);
System.out.println("You chose " + chosenProduct.getName() + "!");
if (money < chosenProduct.getPrice()) {
    System.out.println("This is not enough money to buy this product");
} else {
    System.out.println(" Price = " + chosenProduct.getPrice() + "  Your change = " + (money - chosenProduct.getPrice()));
}

This is a common moment in programming and you're right to think there's a better way to go about it.这是编程中的一个常见时刻,您认为有更好的方法是正确的。

In your particular case, where you have a similar structure of code in many places, you should try using a function.在您的特定情况下,您在许多地方都有类似的代码结构,您应该尝试使用函数。 Try writing a private function in the same class that takes in some of the parameters that change.尝试在同一个类中编写一个私有函数,该函数接受一些更改的参数。 Depending on the level of complexity you end up with you might end up with a large function with a lot of parameters which isn't great either.根据您最终的复杂程度,您可能最终会得到一个带有很多参数的大型函数,这也不是很好。 Regardless, writing a function is probably the first place you should go when you encounter this situation.无论如何,当您遇到这种情况时,编写函数可能是您首先应该去的地方。

Secondarily, consider what this segment of code is doing.其次,考虑这段代码在做什么。 Making a generic function to replace the whole code segment might not be ideal but could you easily write a function to do a small part of it?制作一个通用函数来替换整个代码段可能并不理想,但是您能否轻松编写一个函数来完成其中的一小部分? If so, is it now easy to make the rest into another function?如果是这样,现在是否可以轻松地将其余部分变成另一个功能? Keep track of any variances you have across your many similar code segments, if any, and try to create functions that address those variations.跟踪您在许多类似代码段中的任何差异(如果有),并尝试创建解决这些差异的函数。

Finally, depending on what is in scope for your current level of programming, you might be able to create data structure to help with the identification of the choice.最后,根据您当前编程水平的范围,您可能能够创建数据结构来帮助识别选择。 For example, maybe you could make a map where you could store each of the choices and an associated object that contains all of the data you need to respond to the user (ie cost, item name, etc.).例如,也许您可​​以制作一个地图,在其中存储每个选项和一个关联对象,其中包含您需要响应用户的所有数据(即成本、项目名称等)。 With that kind of approach you can pre-populate all of those options in a straightforward manner and have your code simply look up the set of data associated with the choice and call of function to print the necessary output.使用这种方法,您可以以一种直接的方式预先填充所有这些选项,并让您的代码简单地查找与函数的选择和调用相关的数据集以打印必要的输出。

Ultimately, how you go about this and future situations like it is highly dependent upon what your level of experience with programming, how many choices there are, and how complex the data associated with each choice is.归根结底,您如何处理这种情况以及类似的未来情况在很大程度上取决于您的编程经验水平、有多少选择以及与每个选择相关的数据的复杂程度。

Continue to trust your instincts though, they will serve you well.继续相信你的直觉,它们会很好地为你服务。

Switch case is the desired functionality. 开关盒是所需的功能。
 
 
 
  
  switch(choice) { case 'a' : <some code> break; case 'b': <some other code> break; default: <if none of the choices matched> }
 
 

The only caveat is that your choice value has to be a char or an int 唯一需要注意的是,您的选择值必须是 charint


EDIT :编辑

  • This was a bad answer from my side.这对我来说是一个糟糕的答案。 Clearly, you need a more cleaner way to write your vending machine.显然,您需要一种更简洁的方式来编写自动售货机。
  • A good way to structure it would be to first create a Product class which can store the name and the price of the product.构建它的一个好方法是首先创建一个 Product 类,该类可以存储产品的名称和价格。
public static Main(String[] args) {
    // ...
    private Product processUserInput(String productName) {
        // Add logic to process the string and return a Product
    }
    // ...
}
  • You could then create a function (which could be used in your main() ) which takes the text input from your user and map it to an actual product.然后,您可以创建一个函数(可以在您的main() ),它从您的用户那里获取文本输入并将其映射到实际产品。
public static Main(String[] args) {
    // ...
    private int processUserProductChoice(Product product, int amountAvailable) {
        // Add logic to process the product and amount
        // Probably use switch case now.
    }
    // ...
}
  • Then you could add a function that would process the Product and the amount the user has and return the change remaining or maybe -1 if the product costs more than the available amount.然后,您可以添加一个函数来处理Product和用户拥有的金额,并返回剩余的零钱,如果产品成本超过可用金额,则返回 -1。
 public static Main(String[] args) { // ... private int processUserProductChoice(Product product, int amountAvailable) { // Add logic to process the product and amount // Probably use switch case now. } // ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM