写一个商品类然后里面有商品姓名和商品价格商品数量 在main方法里面键盘输入商品类的商品,最后打印出来商品清单
时间: 2024-06-10 13:05:11 浏览: 20
好的,我可以帮您解决这个问题。以下是一种可能的解决方案:
```java
import java.util.Scanner;
class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
public class ProductDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入商品数目:");
int count = scanner.nextInt();
Product[] products = new Product[count];
for (int i = 0; i < count; i++) {
System.out.println("请输入第 " + (i + 1) + " 个商品信息:");
System.out.print("商品名称:");
String name = scanner.next();
System.out.print("商品价格:");
double price = scanner.nextDouble();
System.out.print("商品数量:");
int quantity = scanner.nextInt();
products[i] = new Product(name, price, quantity);
}
System.out.println("\n商品清单:");
for (int i = 0; i < count; i++) {
System.out.println(products[i].getName() + "\t" + products[i].getPrice() + "\t" + products[i].getQuantity());
}
}
}
```
以上代码中,我们定义了一个 Product 类,包含了商品名称、价格和数量三个属性,并提供了相应的 getter 和 setter 方法。在 main 方法中,我们通过键盘输入构造多个 Product 对象,并将它们存储在一个 Product 数组中。最后,我们遍历数组,打印出所有商品的信息。
您可以尝试运行该代码,并根据自己的需要进行修改。希望对您有所帮助!