理解面向对象 从键盘获取{"宝马",10.00,"red";"老年代步车",1.00,"blue":"电动车",0.05,"red"}
1.汽车类
package com.fqs.demo1; public class Car { private String brand; private Double price; private String color; //没有参数 public Car(){ } //全部参数 public Car(String brand,Double price,String color){ this.brand=brand; this.price=price; this.color=color; } //setBrand public void setBrand(String brand) { this.brand=brand; } //getBrand public String getBrand() { return brand; } //setPrice public void setPrice(Double price) { this.price=price; } //getPrice public Double getPrice() { return price; } //setColor public void setColor(String color) { this.color=color; } //getColor public String getColor() { return color; } }
对象
package com.fqs.demo1; import java.util.Scanner; public class CarTest { public static void main(String[]args) { //1.定义一个数组arr存放3个车的信息{"宝马,30.00,红色","宝马2,30万,红色","宝马2,30万,红色"} Car []arr=new Car[3]; //2.数据sc来源是键盘 Scanner sc=new Scanner(System.in); //3.循环做 for(int index=0;index<arr.length;index++) { //初始化对象 Car c=new Car(); //3.1放品牌sc值到数组内 意思是arr[0].setBrand但是不能这样写 //正确的做法是c.setBrand(键盘输入的值);第4步骤将arr[0]=c; //3.1.1提示写入品牌 System.out.println("请输入品牌"); String b=sc.next(); c.setBrand(b); //3.2放价格sc值到数组内arr[0].setPrice但是不能这样写 System.out.println("请输入价格"); Double p=sc.nextDouble(); c.setPrice(p); //3.3放颜色sc值到数组内arr[0].setColor但是不能这样写 System.out.println("请输入颜色"); String co=sc.next(); c.setColor(co); //4.将品牌 价格 颜色放到类Car中 arr[index]=c; } //5.输出整个arr for(int index=0;index<arr.length;index++) { Car c=arr[index]; System.out.println(c.getBrand()+""+c.getPrice()+""+c.getColor()); } } }
浙公网安备 33010602011771号