【问题标题】:Checking Input Against Items in a String Array in Java在 Java 中根据字符串数组中的项目检查输入
【发布时间】:2024-04-26 15:05:02
【问题描述】:

我正在为我的大学作业编写以下代码。我被要求使用我正在使用的数组。我被要求使用我已经在做的 for 循环和 if 语句。我想出了以下代码:

class HardwareStore2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.printf("%55s", "**WELCOME TO THE HARDWARE STORE**\n");
        System.out.printf("%55s", "=================================\n");

        String [] codes = {"G22", "K13", "S21", "I30"};
        String [] description = {"STICKY Construction Glue", "CAR-LO Key Ring", "SCREW-DUP Screwy Screws", "LET-IT-RAIN Padlock"};
        List<String> codeList = Arrays.asList(codes);
        String output = "";
        int i = 1000;
        String [] userCode = new String[i];
        char dolSymb = '$';
        int [] pricesAndTax = {10989, 5655, 1099, 4005, 20};
        int [] weight = {};
        int [] userQuantity = {1};
        int [] userPrice = new int[i];
        int userStickyPrice = 0;
        int userKeyringPrice = 0;
        int userScrewyPrice = 0;
        int userPadlockPrice = 0;
        int userPreWithTax = 0;
        int userTotal = 0;
        int userPreTotal = 0;
        int userShipping = 0;

        System.out.printf("%-10s%-40s%-15s%-10s\n", "CODE", "DESCRIPTION", "WEIGHT", "PRICE\n");
        System.out.printf("%-10s%-55s%s%d.%02d\n", codes[0], description[0], dolSymb, pricesAndTax[0]/100, pricesAndTax[0]%100);
        System.out.printf("%-10s%-55s%s%d.%02d\n", codes[1], description[1], dolSymb, pricesAndTax[1]/100, pricesAndTax[1]%100);
        System.out.printf("%-10s%-55s%s%d.%02d\n", codes[2], description[2], dolSymb, pricesAndTax[2]/100, pricesAndTax[2]%100);
        System.out.printf("%-10s%-55s%s%d.%02d\n", codes[3], description[3], dolSymb, pricesAndTax[3]/100, pricesAndTax[3]%100);

        System.out.println("PLEASE ENTER YOUR ORDER:");
        System.out.print("NAME: ");
        String username = in.nextLine();
        System.out.print("ADDRESS Line 1: ");
        String address1 = in.nextLine();
        System.out.print("ADDRESS Line 2: ");
        String address2 = in.nextLine();
        System.out.print("POSTAL CODE: ");
        String postalcode = in.nextLine();

        for (i = 0;; i++) {
            System.out.print("CODE (X to QUIT):");
            userCode[i] = in.nextLine();

            if (userCode[i].equalsIgnoreCase("x")) {
                break;
            }

            System.out.print("QUANTITY: ");
            userQuantity[i] = in.nextInt();
            in.nextLine();

            if (userCode[i].equalsIgnoreCase(codes[0])) {
                userStickyPrice += userQuantity[i]*pricesAndTax[0];

            }
            else if (userCode[i].equalsIgnoreCase(codes[1])) {
                userKeyringPrice += userQuantity[i]*pricesAndTax[1];

            }
            else if (userCode[i].equalsIgnoreCase(codes[2])) {
                userScrewyPrice += userQuantity[i]*pricesAndTax[2];

            }
            else if (userCode[i].equalsIgnoreCase(codes[3])) {
                userPadlockPrice += userQuantity[i]*pricesAndTax[3];

            }
            else if (!codeList.contains(userCode)) {
                i = i - 1;
            }
        }
     }
}

现在,一切都与一百万个 if 和 else 无缝协作,但我想知道是否有办法用一个或两个执行类似操作的 if-else-if 语句替换所有语句:

if (userCode[i].contains(codes[0], codes[1], codes[2], codes[3] {}

或者更好的东西,比如:

if (userCode.contains(any.one.item.in.codeList) {
    then.get.the.price.of.that.item.and.do.item.specific.operations
    }

如果问题不够清楚,请告诉我。再说一次,这是一项大学作业,所以我希望得到解释。

【问题讨论】:

    标签: java arrays string if-statement


    【解决方案1】:

    无需更改其余数据结构以提高效率(例如,Map),您可以使用单个 if 和嵌套循环实现相同的效果:

    boolean found = false;
    for (int j = 0 ; !found && j != codes.length ; j++) {
        if (userCode[i].equalsIgnoreCase(codes[j])) {
            userScrewyPrice += userQuantity[i]*pricesAndTax[j];
            found = true;
        }
    }
    if (!found) {
        i--;
    }
    

    【讨论】:

    • 如果“地图”更好,那么我确实有时间和精力朝那个方向看。由于我是 Java 新手,你是指 Hashmaps 还是我完全不在这儿?
    • @nickecarlo Hashmap 是正确的,只要确保您使用通用版本 Hashmap&lt;K,T&gt;(它为您提供更好的类型安全性)。您将定义一个局部变量,如下所示:Map&lt;String,Integer&gt; codeToPriceAndTax = new HashMap&lt;String,Integer&gt;; 然后您将在初始化期间将代码/价格+税对添加到该映射。在您的主循环中,您将使用int priceAndTax = codeToPriceAndTax.get(userCode[i]) 通过他们的代码循环价格+税。
    【解决方案2】:

    变量codeList 是一个List,它有一个contains 函数,如果我理解你想要做什么,它会很有帮助。

    此外,由于Java 7,您可以使用字符串作为switch 语句的参数,这将使您的代码看起来更好。

    【讨论】:

      【解决方案3】:

      我没有阅读完整的问题,所以这可能只是部分答案......但你问你是否可以使用:

      if (userCode[i].contains(codes[0], codes[1], codes[2], codes[3] {}
      

      你可以使用类似...

      if(new string[]{"a","b","c"}.Contains("a")) {}
      

      或将其放入自定义数组类型中...

      arrayType[] a = new arrayType[]{item1, item2, item3}
      if (arrayType.Contains(searchItem)) {}
      

      基本上 - 你可以做你所要求的,只需要改变语法的顺序。但是,我敢肯定,这只是让您思考的部分答案。

      【讨论】:

        【解决方案4】:

        如果您有多个“if”语句,您也应该考虑使用“switch”语句。

        看起来 switch 语句会在这里节省很多行。

        【讨论】: