我有一个代表产品的Product类:
import java.util.ArrayList;
public class Product {
private int productId;
private String productType;
private String brand;
private double price;
public Product(int productId, String productType, String brand, double price)
{
this.productId = productId;
this.productType = productType;
this.brand = brand;
this.price = price;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductType() {
return this.productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getBrand() {
return this.brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
}
现在,在我的程序中,我想创建这个Product类的3个随机对象,这是我的代码:
public static void main(String[] args) {
ArrayList<Product> products = new ArrayList();
Random r = new Random();
for(int i = 0; i < 3; i++)
{
products.add(new Product(1337, "Type", "Brand", 300.33));
}
}
现在,我的问题是如何实现以便随机类创建随机值?我已经为产品创建了静态值,那么如何将其随机化,以便获得3个不同的值?
答案 0 :(得分:1)
在不知道要随机化Product
的哪个元素的情况下,人们只能继续猜测。下面给出的代码不是您问题的解决方案;而是为您提供有关如何使用随机生成的值的指针:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Product {
private int productId;
private String productType;
private String brand;
private double price;
public Product(int productId, String productType, String brand, double price) {
this.productId = productId;
this.productType = productType;
this.brand = brand;
this.price = price;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductType() {
return this.productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getBrand() {
return this.brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product [productId=" + productId + ", productType=" + productType + ", brand=" + brand + ", price="
+ price + "]";
}
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
Random r = new Random(10);
int num;
for (int i = 0; i < 3; i++) {
num = r.nextInt(10);
products.add(new Product(r.nextInt(10000), "Type" + num, "Brand" + num, 1000 * r.nextDouble()));
}
products.stream().forEach(System.out::println);
}
}
示例运行:
Product [productId=2380, productType=Type3, brand=Brand3, price=257.8027905957804]
Product [productId=1456, productType=Type6, brand=Brand6, price=244.11725056425314]
Product [productId=6214, productType=Type1, brand=Brand1, price=370.6111260136414]
如有需要,请随时发表评论。