题目要求:
一个小练习
/*定义数组存储3个商品对象
* 商品的属性:商品的id,名字,价格,数量
* 创建三个商品对象,并把商品对象存入数组当中
* */
在eclipse里面创建一个名为Text3的包,里面新建两个类,一个为Good类,一个为GoodText类
在Good里面的代码为:
package text3;
/*定义数组存储3个商品对象
* 商品的属性:商品的id,名字,价格,数量
* 创建三个商品对象,并把商品对象存入数组当中
* */
public class Good {
private String id;
private String name;
private double price;
private int count;
//构建空参方法
public Good() {
}
public Good(String id,String name,double princ,int count) {
this.id=id;
this.name=name;
this.price=price;
this.count=count;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id=id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price=price;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count=count;
}
}
在GoodText里面的代码为:
package text3;
public class GoodText {
public static void main(String[]args) {
//1.创建一个数组
Good[] arr=new Good[3];
//2.创建三个商品对象
Good g1=new Good("001","华为P40",999,100);
Good g2=new Good("002","保温杯",50,200);
Good g3=new Good("003","枸杞",20,40);
//3.把创建的商品对象存储到数组中
arr[0]=g1;
arr[1]=g2;
arr[2]=g3;
//4遍历
for( int i=0;i<arr.length;i++) {
//i 索引 arr[i] 数组中的元素
Good good=arr[i];
System.out.println(good.getId()+","+good.getName()+","+good.getPrice()+","+good.getCount());
}
}
}
最后的运行结果为: