【发布时间】:2026-02-13 04:40:02
【问题描述】:
我有一个类ProductMaster,我想创建它并添加到for 循环中的列表中,接收来自控制台的输入。
类如下:
public class ProductMaster {
String productName;
double productPrice; // ... so on
ProductMaster() { }
ProductMaster(String prodN, double prodP, int discQ, double discP) {
productName=prodN;
// ...
}
public static void main(String[] args) {
// ... hardcoded values for example
// ... trying to achieve this dynamically by using a for loop,
// ProductMaster milk = new ProductMaster("Milk",3.97,2,5.00)
// list.add(milk);
// trying to create the above two lines by using for loops
for (int i=0; i<n; i++) {
System.out.println("Enter the item name:");
String n1 = br.readLine();
System.out.println("Enter the item price:");
Double n2 = Double.parseDouble(br.readLine());
// taking input from console
ProductMaster n12 = new ProductMaster(n12, n2, n3, n4);
list.add(new ProductMaster(n12, n2, n3, n4));
}
}
}
【问题讨论】:
标签: java class object constructor