[英]Program repeats user input even when an equivalency condition / the first if-statement has been met
我需要在我的程序中使用一個實例來工作,如果用戶輸入的付款編號( payment
)等於帶稅結帳的總價( price3
),則程序將僅列出 0.00 作為更改而不重復用戶輸入就好像用戶的付款低於價格一樣。 但是,當payment
等於price3
( payment - price3 == 0
) 時,程序將轉到else-if
語句。 我該如何解決?
示例:price3 == 28,payment == 28,payment input 后的輸出是“你還欠……”等等,而不是“你的零錢是 $0.00”。
我認為它跳過了 while 循環中的第一個 if 語句,但我不知道為什么。 我已經嘗試在 while 循環中移動 if 語句無濟於事。
沒有錯誤消息。
注意:我仍在努力學習 Java。 最近才開始。
我的問題引用的程序代碼如下所示:
import java.util.Scanner;
public class Checkout
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many items are you purchasing?");
int count = input.nextInt();
double price1 = 0;
double price2 = 0;
String userItem = "";
for(int i = 1; i<=count; i++)
{
System.out.println("Please enter the name of the item:");
input.nextLine();
userItem = input.nextLine();
System.out.println("Please enter the price of the item:");
price1 = input.nextDouble();
System.out.println();
System.out.printf("Your item #" + i + " is " + userItem + " with a price of $" + "%.2f", price1);
System.out.println();
price2 = price2 + price1;
}
System.out.println();
System.out.printf("Your total amount is: $" + "%.2f", price2);
double price3 = price2 + (price2 * 0.06);
System.out.println();
System.out.printf("Your total amount with tax is: $" + "%.2f", price3);
System.out.println();
System.out.println("I need a payment!");
double payment = input.nextDouble();
boolean condition = false;
while(condition == false)
{
if(payment - price3 == 0)
{
condition = true;
}
else if(payment < price3)
{
System.out.println();
System.out.printf("You still owe " + "%.2f", (price3-payment));
System.out.println();
System.out.println("I need a better payment!");
payment = input.nextDouble();
}
else
{
condition = true;
}
}
double change = payment - price3;
System.out.println();
System.out.printf("Your change is: $" + "%.2f", change);
}
}
您問題的核心在於 (1) 期望浮點值完全相等,以及 (2) 將數量顯示為 2 位小數。
假設用戶被告知要支付的金額 (price3) 使用 2 位小數,即使他輸入與支付完全相同的值,它也可能與 price3 的真實值不匹配。
理想情況下,您應該以便士(或該貨幣的任何較小單位)進行所有計算。 否則,您支付正確金額的標准應該是價格和付款之間的差異小於 0.01。
在所述情況下
示例:price3 == 28,payment == 28,payment input 后的輸出是“你還欠……”等等,而不是“你的零錢是 $0.00”。
如果稅前價格為 26.415,則稅后價格為 27.9999,顯示為 28.00 但不等於 28.00。 26.41 和 26.42 都不能使您達到 28.00 的稅后顯示價格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.