Java中检查输入是否匹配字符串数组中的项

3
我有以下代码,是为我大学的作业而编写的。我被要求使用数组,我已经在使用了。我被要求使用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
    }

请告知如果问题不够清晰。再次说明,这是一项大学作业,因此需要解释。
4个回答

4

不需要改变其它数据结构(比如更加高效的 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--;
}

如果“Map”更好,那么我有时间和精力去研究它。因为我是Java的新手,您是指HashMap还是我完全搞错了? - Nico
1
@nickecarlo Hashmap是正确的,只需确保您使用通用版本Hashmap<K,T>(它可以提供更好的类型安全性)。 您将定义一个本地变量,如此:Map<String,Integer> codeToPriceAndTax = new HashMap<String,Integer>; 然后在初始化过程中向该映射添加代码/价格+税对。 在您的主循环内,您将使用int priceAndTax = codeToPriceAndTax.get(userCode[i])来通过它们的代码查找价格+税。 - Sergey Kalinichenko

2
变量 codeList 是一个 List ,它有一个 contains 函数,如果我理解你的意思,这可能很有帮助。
此外,自 Java 7 以来,您可以将字符串用作 switch 语句的参数,这会使您的代码看起来更漂亮。

2

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

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)) {}

基本上,你可以实现你所要求的,只需要改变语法的顺序。但是,我相信这只是一个部分答案,能够帮助你思考。


1

每当您有多个“if”语句时,也应考虑使用“switch”语句。

看起来使用switch语句可以节省相当多的行数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接