有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将数组对象及其变量列表到Main方法

好吧,伙计们,我是新来的,但是我已经在无数不同的场合使用过这个网站,试图找到解决问题的方法。我有一个汽车库存计划,我正在为学校工作。本质上,我使用setter和getter将对象添加到汽车类中的ArrayList中

我在编写listAllVehicles方法时遇到了很多麻烦。起初,我可以在vehicles arraylist中列出车辆,但它会给我一个指向该对象的指针。所以它看起来有点像这个com。automobile@1662365.我想在Automobile类中创建一个名为listAllVehicles的循环方法,该方法循环遍历数组列表并打印每个车辆的简短描述,直到完成列表。我在编写代码方面取得了一些进展,但它不起作用,for循环也没有初始化。我相信你们会知道我到底做错了什么

我的代码目前还没有设置为格式化打印内容的ToString方法,但我愿意接受这个想法(已经尝试过了,但还没有找到答案)

任何帮助都将不胜感激。谢谢大家

我已经试着用一根弦来演奏了。我在for循环中对一个对象进行了转换。真的有很多不同的东西,但我似乎无法让这些都发挥作用

public static void main(String[] args) {
        String model, make, color;
        int year = 0;
        int mileage = 0;
        Scanner userInput = new Scanner(System.in);

        System.out.println("[1]Add a Vehicle\n[2]List All 
        Vehicles\n[3]Update a Vehicle\n[4]Delete a Vehicle\n[5]Quit\n");
        System.out.print("Please choose from an option above: ");
        int userChoice = userInput.nextInt();
        switch(userChoice) {
        case 1:
            Scanner addVehicleScanner = new Scanner(System.in);
            Automobile newVehicle = new Automobile();
            System.out.print("What is the vehicle make: ");
            make = addVehicleScanner.next();
            newVehicle.setMake(make);
            System.out.print("What is the vehicle model: ");
            model = addVehicleScanner.next();
            newVehicle.setModel(model);
            System.out.print("What is the vehicle color: ");
            color = addVehicleScanner.next();
            newVehicle.setColor(color);
            System.out.print("What is the vehicle year: ");
            year = addVehicleScanner.nextInt();
            newVehicle.setYear(year);
            System.out.print("What is the vehicle mileage: ");
            mileage = addVehicleScanner.nextInt();
            newVehicle.setMileage(mileage);
            newVehicle.addVehicle(newVehicle);
            vehicleInventory.main(args);
            break;
        case 2:
            Automobile printAllVehicles = new Automobile();
            printAllVehicles.listAllVehicles();
            break;
        case 3:
            //FIX ME: Add Update Vehicle Code
            break;
        case 4:
            //FIX ME: Add Delete Vehicle Code
            break;
        case 5:
            System.out.println("\n\nGoodbye!");
            break;




public void listAllVehicles() {
        Automobile temp = new Automobile();
        for (int i = 0; i < vehicles.size(); i++) {
            temp = (Automobile) vehicles.get(i);
            System.out.println(temp);
        }
    }

共 (1) 个答案

  1. # 1 楼答案

    为使代码正常工作提供一些建议

    1)重写Automobile类的toString方法,并返回汽车对象的完整细节,这样当您对Automobile的对象调用System.out.println时,它会提供该细节

    @Override
    public String toString() {
    return "Automobile [ model "+ model +"]";
    }
    

    2)不要像vehicleInventory.main(args)那样调用main方法。主要方法是由JVM调用,作为类的起点。在代码中,可以使用while循环,而不是调用它