【问题标题】:Java how to save user input in arrayJava如何将用户输入保存在数组中
【发布时间】:2021-07-29 17:51:52
【问题描述】:

不确定如何将用户输入保存到数组 reg[i] 中。 如何将它们保存到 reg[i] 中,以便我可以通过 toString 方法打印出来。

包含4个java类。 Owner, Car(CarType), CarType 和 Register(Owner, Car)。

public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        
        CarType[] type = {new CarType("Toyota", "Vios", 1.5)
                          , new CarType("Nissan","Teana",2.0)
                          , new CarType("Honda ","City", 1.6)};
        
        Register[] reg = new Register[3];  
        
        for(int i=0; i<reg.length; i++){
            //registration Number
            System.out.println("Registration Numnber" + Register.getnextRegNo());
            
            //owner name and ic
            System.out.print("Enter owner's name: ");
            String name = in.nextLine();
            System.out.print("Enter IC number: ");
            String ICNo = in.next();
            Owner owner= new Owner(name, ICNo);
            
            //car info
            System.out.print("Enter plate No: ");
            String plateNo = in.next();
            System.out.print("Enter color: ");
            String color = in.next();
            System.out.print("Enter year: ");
            int year = in.nextInt();
            
            //car type choose
            System.out.println("\nCar Types:");
            for(int j=0; j<type.length; ++j){
                System.out.println((j+1)+"."+type[j]);
            }
            System.out.println("\nSelect car type[1...3]: ");
            int select = in.nextInt();
            CarType carType = type[select-1];
            Car car=new Car(plateNo, color, year, carType);
            
            //my thought is add some code here to save the inputs
        }
        
        System.out.println("\t\t\t\t\tCar Registration Listing");
        System.out.println("Reg No.\tName\t\tIC No.\t\tPlate No.\tColor\tYear\tMake\tModel\tCapacity");
        for(int k=0; k<reg.length; k++){
            System.out.println(reg[k].toString());
        }
        
    }

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    假设Register 类在构造函数参数中采用OwnerCar

    您已经正确声明了数组reg,现在您只需为其赋值即可。

    你可以这样做

    reg[i] = new Register(owner, car);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2014-06-04
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多