首页 > 解决方案 > Java如何将用户输入保存在数组中

问题描述

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

包含4个java类。所有者,汽车(汽车类型),汽车类型和注册(所有者,汽车)。

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());
        }
        
    }

标签: javaarrays

解决方案


假设Register该类采用Ownerand Carin 构造函数参数。

你已经reg正确地声明了数组,现在你只需要给它赋值。

你可以这样做

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

推荐阅读