I'm trying to write code that takes valid input ($0.05, $0.10, $0.20, $0.50, $1.00, $2.00, $5.00, $10.00, $20.00, $50.00, $100.00) and outputs any remainder, with output code similar to:
$38.00 remains to be paid. Insert money: $20.00
You gave $20.00.
$18.00 remains to be paid. Insert money: 3
Invalid value. Try again.
$18.00 remains to be paid. Insert money: $9
Invalid value. Try again.
$18.00 remains to be paid. Insert money: $10.00
You gave $30.00
$8.00 remains to be paid. Insert money: $8.00
Invalid value. Try again.
Unfortunately at the moment, when I enter an integer like '3', it sometimes outputs "empty string" and sometimes outputs "Invalid value. Try again." but still takes the value of the integer as part of paidTotal i.e
$18.00 remains to be paid. Insert money: $10.00
You gave $10.00.
$8.00 remains to be paid. Insert money: 4
empty String
$8.00 remains to be paid. Insert money: $2.00
You gave $10.00.
$8.00 remains to be paid. Insert money: 9
empty String
$8.00 remains to be paid. Insert money: 9
Invalid value. Try again.
$8.00 remains to be paid. Insert money: $5.00
You gave $10.00.
$8.00 remains to be paid. Insert money: $2.00
You gave $12.00
$6.00 remains to be paid. Insert money:
Here's the relevant section of my code. Any help would be greatly appreciated!
System.out.print("$" + formatter.format(priceSum) + " remains to be paid. Insert money: ");
String moneyEntered = keyboard.nextLine();
System.out.println("");
String noDollar = moneyEntered.substring(1);
double moneyAsDouble = Double.parseDouble(noDollar);
double paidTotal = 0;
paidTotal += moneyAsDouble;
List validMoney = Arrays.asList("$0.05", "$0.10", "$0.20", "$0.50", "$1.00", "$2.00", "$5.00", "$10.00", "$20.00", "$50.00", "$100.00");
boolean moneyEnteredFound = true;
while(true) {
if (validMoney.contains(moneyEntered)) {
while (paidTotal < priceSum) {
if (validMoney.contains(moneyEntered)) {
System.out.println("You gave $" + formatter.format(paidTotal));
System.out.print("$" + formatter.format(priceSum - paidTotal) + " remains to be paid. Enter coin or note: ");
moneyEntered = keyboard.nextLine();
noDollar = moneyEntered.substring(1);
moneyAsDouble = Double.parseDouble(noDollar);
paidTotal += moneyAsDouble;
} else {
System.out.println("Invalid value. Try again.");
System.out.print("$" + formatter.format(priceSum - paidTotal) + " remains to be paid. Enter coin or note: ");
moneyEntered = keyboard.nextLine();
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire