java输入购物清单,包括商品名数量单价,输出每样商品金额,输入折扣,计算最终金额找零并输出
时间: 2024-10-21 10:11:40 浏览: 20
CalcChange:分配1-用户输入硬币,程序输出美元找零金额
在Java中,你可以创建一个更交互式的程序来接收用户的输入,包括商品名、数量和单价,然后计算每件商品的金额,接着获取折扣率,计算最终总金额并找出找零。这里是一个简单的例子,使用Scanner类来读取用户输入:
```java
import java.util.Scanner;
class Product {
String name;
int quantity;
double unitPrice;
public Product(String name, int quantity, double unitPrice) {
this.name = name;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
public double getTotalCost() {
return quantity * unitPrice;
}
@Override
public String toString() {
return name + ": " + quantity + " x $" + unitPrice + ", 总价: $" + getTotalCost();
}
}
class DiscountCalculator {
private Scanner scanner;
private double totalCost;
private double discountRate;
public DiscountCalculator() {
scanner = new Scanner(System.in);
}
public void inputProducts() {
System.out.println("请输入商品信息(按q退出):");
while (scanner.hasNext()) {
String input = scanner.nextLine();
if (input.equalsIgnoreCase("q")) break;
String[] parts = input.split(",");
String name = parts[0];
int quantity = Integer.parseInt(parts[1]);
double unitPrice = Double.parseDouble(parts[2]);
Product product = new Product(name, quantity, unitPrice);
totalCost += product.getTotalCost();
System.out.println(product);
}
}
public void inputDiscount() {
System.out.println("请输入折扣率(百分比形式):");
discountRate = scanner.nextDouble();
}
public double calculateFinalCostAndChange() {
double discountedTotal = totalCost * (1 - discountRate / 100);
double change = Math.abs(discountedTotal - totalCost);
System.out.printf("折扣后的总价: $%.2f, 找零: $%.2f\n", discountedTotal, change);
return discountedTotal;
}
public static void main(String[] args) {
DiscountCalculator calculator = new DiscountCalculator();
calculator.inputProducts();
calculator.inputDiscount();
calculator.calculateFinalCostAndChange();
}
}
```
在这个例子中,用户输入商品信息直到选择退出,然后输入折扣率,最后计算并显示最终费用及找零。
阅读全文