- 定义数组存储三个商品对象,商品的属性:id,名字,价格,库存,创建三个商品对象,并把商品对象存入到数组中
public class Goods {
private String 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;
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;
}
}
public class GoodsTest {
public static void main(String[] args) {
//创建一个数组,动态初始化
Goods[] arr = new Goods[3];
//创建三个商品对象
Goods g1 = new Goods("001","华为mate60",5999.0,100);
Goods g2 = new Goods("002","保温杯",227.0,200);
Goods g3 = new Goods("003","宁夏枸杞",12.7,70);
//把商品添加到数组
arr[0] = g1;
arr[1] = g2;
arr[2] = g3;
for (int i = 0; i < arr.length; i++) {
Goods goods = arr[i];
System.out.println(goods.getId() + ", " + goods.getName() + ", " + goods.getPrice() + ", " + goods.getCount());
}
}
}
定义数组存储3部汽车对象,汽车的属性:品牌,价格,颜色。创建三个汽车对象,数据通过键盘录入而来,并把数据存入到数组中。
- 键盘录入
- Java里面有一个类叫Scanner,可以接收键盘输入的数字
- 第一步:导包,找Scanner这个类
- import java.util.Scanner;
- 导包必须在类定义的上边(public class上面)
- 第二步:创建对象,开始使用Scanner这个类
- Scanner sc = new Scanner(System.in);
- sc为变量名可以改变,其他不能改
- 第三步:接收数据
- int i = sc.nextInt();
- i为变量名可以改变,其他不能改
- 注意:这种方式只能接收整数,输入字符小数会报错
- 第一套体系(遇到空格、制表符、回车就停止接收,后面的数据不接收)
- nextInt(); 接收整数
- nextDouble(); 接收小数
- next(); 接收字符串
- 第二套体系(可以接收空格、制表符,遇到回车才停止接收)
- nextLine(); 接收字符串
- 两套体系不能混用,容易出错
public class Car {
private String brand;
private int price;
private String color;
public Car() {
}
public Car(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 CarText {
public static void main(String[] args) {
//创建一个数组存储汽车对象
Car[] arr = new Car[3];
//创建汽车对象,数据来自键盘录入
Scanner sc = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
//创建汽车的对象
Car c = new Car();
//录入品牌
System.out.println("请输入汽车的品牌");
String brand = sc.next();
c.setBrand(brand);
//录入价格
System.out.println("请输入汽车的价格");
int price = sc.nextInt();
c.setPrice(price);
System.out.println("请输入汽车的颜色");
String color = sc.next();
c.setColor(color);
//把汽车对象添加到数组中
arr[i] = c;
}
//遍历数组
for (int i = 0; i < arr.length; i++) {
Car car = arr[i];
System.out.println(car.getBrand() + ", " + car.getPrice() + ", " + car.getColor());
}
}
}