gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:23:11 24 4
gpt4 key购买 nike

我编写了一部分代码来获取用户输入,将其与字符串值匹配,然后使用相关的 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:");
}
}
}

问题是,当它获取用户输入时,它不匹配除 $0.05 之外的任何字符串值。在我看来,它没有正确遍历数组,但我不明白为什么。有人能看出这里有问题吗?

最佳答案

这是您问题的可能解决方案

    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 将继续执行,直到付款完成。

for循环遍历数组,直到找到合适的付款

  • 如果找到合适的付款,我们会从总和中减去它。在这两种情况下,我们都使用 break 退出 for 循环。没有必要继续寻找。
  • 如果找不到合适的付款 [! 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();
    }

程序将在 (sum < 0) 时结束,在这种情况下 while 循环退出。我使用 println 而不是 print 来提高消息的易读性。

关于java - 正确的用户输入与数组值不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36475834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com