一.题目:
代码:
方法类
public class Goods { private String id;//id private String name;//名字 private double Price;//价格 private int Count;//库存 //构造方法 public Goods() { } public Goods(String id, String name, double price, int count) { this.id = id; this.name = name; Price = price; 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) { Price = price; } public int getCount() { return Count; } public void setCount(int count) { Count = count; } }
测试类
public class Text { public static void main(String[] args) { //商品数组 Goods []a=new Goods[3];//商品数组 Goods g1 = new Goods("01","iPhone15",10000.00,500); Goods g2 = new Goods("02","蛋白粉",320.00,500); Goods g3 = new Goods("03","枸杞",72.00,1000); //装入数组 a[0]=g1; a[1]=g2; a[2]=g3; //打印 for (int i = 0; i < a.length; i++) { Goods goods=a[i];//放入goods System.out.println(goods.getId()+","+goods.getName()+","+goods.getPrice()+","+goods.getCount()); } } }
结果:
01,iPhone15,10000.0,500
02,蛋白粉,320.0,500
03,枸杞,72.0,1000
二. 题目:
代码:
方法类
public class Cat { private String brand;//品牌 private int price;//价格 private String color;//颜色 public Cat() { } public Cat(String brand, int price, String color) { this.brand = brand; this.price = price; this.color = color; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
测试类:
import java.util.Scanner; public class Text { public static void main(String[] args) { Cat[]arr=new Cat[3];//定义数组 Scanner scanner = new Scanner(System.in); for (int i = 0; i < arr.length; i++) { Cat cat = new Cat(); System.out.println("车的品牌"); String brand=scanner.next(); cat.setBrand(brand);//键盘输入 System.out.println("价格"); int price=scanner.nextInt(); cat.setPrice(price); System.out.println("颜色"); String color=scanner.next(); cat.setColor(color); arr[i]=cat;//汽车对象放入数组 } //打印数组 for (int i = 0; i < arr.length; i++) { Cat cat = arr[i]; System.out.println(cat.getBrand()+" "+cat.getPrice()+" "+cat.getColor()); } } }