【发布时间】:2020-01-17 14:32:28
【问题描述】:
我有一个代表产品的产品类:
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 个不同的值?
【问题讨论】:
-
当“相关”代码不使用 Swing 类时,这是一个很好的提示,swing 标记与问题无关。所以不要添加它!
-
您希望随机字符串(类型和品牌)如何?还是随机 id?
-
我投了反对票,因为在谷歌搜索结果的最顶部(“java生成随机字符串”)我发现多篇文章向您展示了如何做到这一点。
-
您是否有一套固定的品牌、ID 等有效值,或者“随机化”对您意味着什么? “MyArbitraryWeirdBrand”足够随机吗?甚至是“khkghfjkbvnmdk”?
-
带有随机数字的静态值是否足够?