面向对象 类Car 对象c

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(键盘输入的值);最后将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());
        }
        
    }

}

 

posted @ 2023-03-08 22:18  胖豆芽  阅读(21)  评论(0编辑  收藏  举报