java 语言创建一个数组,存储一些对象

题目要求:

一个小练习

/*定义数组存储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());
    	 }
     }
}

最后的运行结果为:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Komorebi_9999

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值