简体   繁体   English

正确的用户输入不匹配数组值

[英]Correct user input not matching array values

I've written a portion of code to take a user input, match it to a string value and then use a related double value to make calculations: 我已经编写了一部分代码来接受用户输入,将其与字符串值匹配,然后使用相关的double值进行计算:

double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};
Scanner keyboard = new Scanner(System.in);

for (int i = 0; i < currencytext.length; i++) {
    boolean valid = false;
    while(!valid){
        System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
        String payment = keyboard.next();
        if(payment.equals(currencytext[i])){
            sum = sum - currency[i];
            if(sum == 0) {
                System.out.print("You gave " + payment);
                System.out.print("Perfect! No change given.");
                System.out.print("");
                System.out.print("Thank you" + name + ".");
                System.out.print("See you next time.");
                }
                }
        if(!(payment.equals(currencytext[i]))) {
            System.out.print("Invalid coin or note. Try again. \n");
                }
        if(payment.equals(currencytext[i]) && currency[i] > sum){
            System.out.print("You gave " + payment);
            System.out.print("Your change:");
        }
    }
}   

The problem is that when it gets to user input, it doesn't match any string values except for $0.05. 问题是,当输入用户输入时,除$ 0.05外,它与任何字符串值都不匹配。 It seems to me like its not iterating through the array properly but I can't figure out why. 在我看来,它似乎没有正确地遍历数组,但是我不知道为什么。 Is anyone able to see a problem here? 有人可以在这里看到问题吗?

Too many flaws to point out. 需要指出的缺陷太多。

However, 然而,

When the currencytext[i] does not match payment , it executes this code: currencytext[i]payment不匹配时,它将执行以下代码:

System.out.print("Invalid coin or note. Try again. \n");
System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
payment = keyboard.next();

So, it executes this for all the times that your input does not match currencytext[i] . 因此,它将在您的输入与currencytext[i]不匹配的所有时间执行此操作。 And, in this block, you have 而且,在这个区块中

payment = keyboard.next();

So, it asks for new input, in this block itself. 因此,它在此块本身中要求新的输入。 Hence, you get the said output for all inputs except $0.05 . 因此,您将获得除$0.05以外的所有输入的输出。

As far as $0.05 is concerned, your first if block executes successfully, and prints no output. $0.05而言,您的第一个if块成功执行,并且不输出任何输出。 So, it moves to the next iteration of the while loop, where again, payment remains the same ( $0.05 ), but currencytext[i] becomes $0.10 . 因此,它移至while循环的下一个迭代,在该循环中, payment仍保持不变( $0.05 ),但是currencytext[i]变为$0.10 SO they do not match, and you get the said output. 因此,它们不匹配,您将得到上述输出。

How to correct this: 如何解决这个问题:

With this code, you need to do a lot of corrections. 使用此代码,您需要进行很多更正。

I suggest you again start from scratch. 我建议您再次从头开始。

If it doesn't fit, it sets valid to true, so the code just has the chance to check against the first item at currencytext[0] , which is $0.05 . 如果不合适,则将valid设置为true,因此代码仅可以检查currencytext[0]的第一项,即$0.05 Then !payment.equals(currencytext[i]) is also true, and your code prints the lines there. 然后!payment.equals(currencytext[i])也成立,您的代码将在此处打印行。 Your else if s are also not properly nested. 您的else if也未正确嵌套。

This is a possible solution for your problem 这是您可能遇到的问题的解决方案

    Scanner keyboard = new Scanner(System.in);

    double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
    String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};

    String payment = keyboard.next();

    double sum = 100; // <- Working example - Read sum from keyboard entry

    while (sum > 0) {

        boolean paymentFound = false;

        for (int i = 0; i < currencytext.length; i++) {

            if (payment.equals(currencytext[i])) {

                sum = sum - currency[i];
                paymentFound = true;

                if (sum == 0) {
                    System.out.println("You gave " + payment);
                    System.out.println("Perfect! No change given.");

                    // System.out.print("Thank you" + name + ".");

                    System.out.println("See you next time.");
                    break;
                } else if (sum < 0) {
                    System.out.println("You gave " + payment);
                    System.out.println("Your change:" + (-1 * sum));
                    break;
                }
            }
        }

        if (!paymentFound) {
           System.out.println("Invalid coin or note. Try again. \n");

        }

        if (sum > 0) {
            System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum);
            payment = keyboard.next();
        }
    }

while-loop will continue until the payment is fullfilled. while循环将一直持续到付款完成为止。

for-loop traverse the arrays until a suitable payment is found for循环遍历数组,直到找到合适的付款

  • If suitable payment is found we substract it from sum . 如果找到合适的付款,我们从sum减去它。 We use break to exit the for-loop in both cases. 在两种情况下,我们都使用break退出for循环。 There is no need to keep searching. 无需继续搜索。
  • If no suitable payment is found [ !paymentFound ], we keep on asking. 如果找不到合适的付款[ !paymentFound ],我们会继续询问。

      if (!paymentFound) { System.out.println("Invalid coin or note. Try again. \\n"); } if (sum > 0) { System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum); payment = keyboard.next(); } 

The program will end when (sum < 0), in which case the while-loop exits. 当(sum <0)时,程序将结束,在这种情况下,while循环将退出。 I have use println instead of print to improve message legibility. 我使用println而不是print来提高消息的可读性。

I don't know how you are reading input. 我不知道您如何阅读输入。 One improvement you can do is write reading input code in for loop. 您可以做的一项改进是在for循环中编写读取输入代码。

Scanner scanner = new Scanner(System.in);
for (... ) {
....
String payment = scanner.nextLine();
....
}

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

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