集合,无法添加新元素

时间:2014-07-24 12:21:14

标签: java collections

我正在制作一个简单的程序,它收集了车库。所以我有Car类,它包含1个String字段,1个双字段和3个类的对象(Engine,GearBox,FuelTank)。我还有Garage Class,它包含1个fild,ArrayList of Cars。在具有main函数的MainApp类中,我有菜单方法。一开始我使用Collections方法add()将3个对象添加到我的List中。它到这个地方正常工作。但是当我尝试使用方法addCar在我的Garage类中添加新对象到我的集合时,所有都退出正常,在此选项中它显示我的集合与新元素,但当我尝试再次使用选项显示我的集合时[5]它只显示我在开始时添加的3个元素。排序和删除也不起作用。

Garage.java:

package ua.lviv.anax;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.Scanner;

public class Garage {

    private List<Car> garage = new ArrayList<>();


    public Garage() {
    }

    public void addCar() {
        String model = scanner("Enter car model");
        double consumationOfFuel = Double
                .parseDouble(scanner("Enter fuel consumation in liters per km"));
        double volume = Double.parseDouble(scanner("Enter engine volume"));
        int hp = Integer.parseInt(scanner("Enter engine power"));
        boolean auto = Boolean
                .parseBoolean(scanner("Is your gearbox automatic (true/false)"));
        int gearsCount = Integer.parseInt(scanner("Enter gear count"));
        String gearBoxType = scanner("Enter gearBox type");
        double amountOfFuel = Double
                .parseDouble(scanner("Enter amount of fuel in your tank"));
        double capacity = Double
                .parseDouble(scanner("Enter your tank capacity"));
        this.garage.add(new Car(model, consumationOfFuel, volume, hp, auto,
                gearsCount, gearBoxType, amountOfFuel, capacity));

    }

    public void removeCar(int index) {
        if (indexCheck(index)) {
        } else
            garage.remove(index);
    }

    public void rideCar(int index, int km) {
        if (indexCheck(index)) {
        } else
            garage.get(index - 1).ride(km);
    }

    public void showGarage() {
        for (int i = 0; i < garage.size(); i++) {
            System.out.println(i + 1 + ". " + garage.get(i).getModel() + " "
                    + garage.get(i).getEngine().getVolume() + " " +garage.get(i).getEngine().getHp() +" " +garage.get(i).getFuelTank().getAmount() +" " + garage.get(i).getGearBox().getGearsCount() + " "
                    + garage.get(i).getGearBox().getType());
        }
    }

    public void sortGarage(int indexOfSort) {
        switch (indexOfSort) {
        case 1:
            Collections.sort(this.garage, new ModelComparator());
            break;
        case 2:
            Collections.sort(this.garage, new AmountOfFuelComparator());
            break;
        case 3:
            Collections.sort(this.garage, new VolumeComparator());
            break;
        case 4:
            Collections.sort(this.garage, new GearsCountComparator());
            break;
        default:
            System.out
                    .println("You entered wrong number, please try again and enter correct one");
        }
    }

    @Override
    public String toString() {
        String garageStr = garage.toString();
        return garageStr;
    }

    public List<Car> getGarage() {
        return garage;
    }

    public void setGarage(List<Car> garage) {
        this.garage = garage;
    }

    public boolean indexCheck(int index) {
        if (index <= 0 && index > garage.size()) {
            System.out
                    .println("You entered wrong number, plese try again and enter correct one");
            return true;
        }
        return false;
    }

    public String scanner(String msg) {
        System.out.println(msg);
        @SuppressWarnings("resource")
        Scanner scan = new Scanner(System.in);
        String scannedString = scan.nextLine();
        return scannedString;
    }

}

Car.java:

package ua.lviv.anax;

public class Car {

    private String model;

    private double consumptionOfFuel;

    private Engine engine;

    private GearBox gearBox;

    private FuelTank fuelTank;


    public Car() {
    }
    public Car(String model, double consumptionOfFuel, double volume, int hp, boolean auto, int gearsCount, String gearBoxType, double amount, double capacity){
        this.model=model;
        this.consumptionOfFuel=consumptionOfFuel;
        this.engine=new Engine(volume, hp);
        this.gearBox=new GearBox(auto, gearsCount, gearBoxType);
        this.fuelTank= new FuelTank(amount, capacity);
    }
    public String getModel() {
        return model;
    }
    public void setModel(String model) {
        this.model = model;
    }

    public double getConsumptionOfFuel() {
        return consumptionOfFuel;
    }
    public void setConsumptionOfFuel(int consumptionOfFuel) {
        this.consumptionOfFuel = consumptionOfFuel;
    }
    public Engine getEngine() {
        return engine;
    }
    public void setEngine(double volume, int hp) {
        this.engine = new Engine(volume, hp);
    }
    public GearBox getGearBox() {
        return gearBox;
    }
    public void setGearBox(boolean auto, int gearsCount, String type) {
        this.gearBox = new GearBox(auto, gearsCount, type);
    }
    public FuelTank getFuelTank() {
        return fuelTank;
    }
    public void setFuelTank(double amount, double capacity) {
        this.fuelTank = new FuelTank(amount, capacity);
    }
    @Override
    public String toString() {
        return "Car [model=" + model + ", engine=" + engine + ", gearBox="
                + gearBox + ", fuelTank=" + fuelTank + "]";
    }
    public void ride(int km){
        double kmDone=fuelTank.getAmount()*100/consumptionOfFuel;
        fuelTank.useFuel(km*consumptionOfFuel/100);
        if (fuelTank.getAmount()==0){
            System.out.println("Your out of fuel, you have passed "+kmDone+" kilomeeters");
        }
    }
}

Engine.java:

package ua.lviv.anax;

public class Engine {

    private double volume;

    private int hp;

    public Engine() {

    }

    public Engine(double volume, int hp) {
        this.volume = volume;
        this.hp = hp;
    }

    public double getVolume() {
        return volume;
    }

    public void setVolume(double volume) {
        this.volume = volume;
    }

    public int getHp() {
        return hp;
    }

    public void setHp(int hp) {
        this.hp = hp;
    }

    @Override
    public String toString() {
        return "Engine [volume=" + volume + ", hp=" + hp + "]";
    }



}

Gearbox.java:

package ua.lviv.anax;

public class GearBox {

    private boolean auto;

    private int gearsCount;

    private String type;

    public GearBox() {
    }

    public GearBox(boolean auto, int gearsCount, String type) {
        this.auto = auto;
        this.gearsCount = gearsCount;
        this.type = type;
    }

    public boolean isAuto() {
        return auto;
    }

    public void setAuto(boolean auto) {
        this.auto = auto;
    }

    public int getGearsCount() {
        return gearsCount;
    }

    public void setGearsCount(int gearsCount) {
        this.gearsCount = gearsCount;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "GearBox [auto=" + auto + ", gearsCount=" + gearsCount
                + ", type=" + type + "]";
    }

}

FuelTank.java:

package ua.lviv.anax;

public class FuelTank {

    private double amount;

    private double capacity;

    public FuelTank() {
    }

    public FuelTank(double amount, double capacity) {
        this.amount = amount;
        this.capacity = capacity;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public double getCapacity() {
        return capacity;
    }

    public void setCapacity(double capacity) {
        this.capacity = capacity;
    }

    @Override
    public String toString() {
        return "FuelTank [amount=" + amount + ", capacity=" + capacity + "]";
    }

    public void useFuel(double amount){
        this.amount -=amount;
        if(this.amount<=0){
            this.amount=0;
        }
    }
}

MainApp.java:

package ua.lviv.anax;

import java.util.Scanner;

public class MainApp {

    public static void main(String[] args) {

        new MainApp().menu();
    }

    public void menu(){

        System.out.println("Welcome to garage");

        while(true){
            System.out.println("Please enter [1] to add car:");
            System.out.println("Please enter [2] to remove car:");
            System.out.println("Please enter [3] to ride a car:");
            System.out.println("Please enter [4] to sort cars in garage:");
            System.out.println("Please enter [5] to show garage:");
            System.out.println("Enter [10] to exit.");
            Garage garage = new Garage();
            garage.getGarage().add(new Car("BMW M5", 17.8, 6.0, 575, true, 6, "Tip Tronic", 55, 80));
            garage.getGarage().add(new Car("Mercedes E63", 16.5, 6.3, 565, true, 7, "Tip Tronic", 45, 90));
            garage.getGarage().add(new Car("Audi RS6", 17.5, 5.5, 602, true, 7, "Tip Tronic", 25, 90));
            switch(scanner()){

            case 1:
                garage.addCar();
                garage.showGarage();
                break;

            case 2:
                garage.showGarage();
                System.out.println("Please enter the index of car you want to remove");
                garage.removeCar(scanner());
                break;

            case 3:
                garage.showGarage();
                System.out.println("Please enter number of car you want to ride");
                int index = scanner();
                System.out.println("Please enter number of kilometers you want to go");
                int km=scanner();
                garage.rideCar(index, km);
                break;

            case 4:
                System.out.println("Enter a number of type sort");
                System.out.println("Enter [1] for sort by hp:");
                System.out.println("Enter [2] for sort by amount of fuel:");
                System.out.println("Enter [3] for sort by volume:");
                System.out.println("Enter [4] for sort by gear count:");

                int indexOfSort = scanner();
                garage.sortGarage(indexOfSort);
                break;
            case 5:
                System.out.println(garage);
                System.out.println("==========================");
                break;
            case 10:
                System.exit(0);
            default:
                System.out.println("You entered wrong number, please try again and enter correct one");
            }

        }
    }

    public int scanner(){
        @SuppressWarnings("resource")
        Scanner scan = new Scanner(System.in);
        int scannedInt = scan.nextInt();
        return scannedInt;
    }
}

这是我试图将汽车加入车库:

Please enter [1] to add car:

Please enter [2] to remove car:

Please enter [3] to ride a car:

Please enter [4] to sort cars in garage:

Please enter [5] to show garage:

Enter [10] to exit.
1
Enter car model

VW

Enter fuel consumation in liters per km

5

Enter engine volume

1.2

Enter engine power

55

Is your gearbox automatic (true/false)

true

Enter gear count

5

Enter gearBox type

Basic Auto

Enter amount of fuel in your tank

20

Enter your tank capacity

55

1. BMW M5 6.0 575 55.0 6 Tip Tronic

2. Mercedes E63 6.3 565 45.0 7 Tip Tronic

3. Audi RS6 5.5 602 25.0 7 Tip Tronic

4. VW 1.2 55 20.0 5 Basic Auto

Please enter [1] to add car:

Please enter [2] to remove car:

Please enter [3] to ride a car:

Please enter [4] to sort cars in garage:

Please enter [5] to show garage:

Enter [10] to exit.

5

[Car [model=BMW M5, engine=Engine [volume=6.0, hp=575], gearBox=GearBox [auto=true,

 gearsCount=6, type=Tip Tronic], fuelTank=FuelTank [amount=55.0, capacity=80.0]], 

Car [model=Mercedes E63, engine=Engine [volume=6.3, hp=565], gearBox=GearBox [auto=true, 

gearsCount=7, type=Tip Tronic], fuelTank=FuelTank [amount=45.0, capacity=90.0]], 

Car [model=Audi RS6, engine=Engine [volume=5.5, hp=602], 

gearBox=GearBox [auto=true, gearsCount=7, type=Tip Tronic], fuelTank=FuelTank [amount=25.0, capacity=90.0]]]
==========================


Please enter [1] to add car:

Please enter [2] to remove car:

Please enter [3] to ride a car:

Please enter [4] to sort cars in garage:

Please enter [5] to show garage:

Enter [10] to exit.

10

就像你在选项1之后看到的那样,显示了新的Car,但是在调用选项5之后,它只有3个元素在启动。

2 个答案:

答案 0 :(得分:0)

我把创建Garage对象放到菜单循环中,每次我尝试做下一个动作时,我都在创建新的Garage对象,并在开始时用我的对象填充它。

对不起每个花时间阅读我的代码并寻找错误的人。

答案 1 :(得分:0)

您已在while循环中初始化Garage类对象。循环时把它拿出来。
每次你的while循环执行它都会初始化你的Garage类对象,这会使你的新输入数据被你的三个值覆盖,在while循环开始时初始化。
你应该是:

Garage garage = new Garage();  
 while(true){
            System.out.println("Please enter [1] to add car:");
            System.out.println("Please enter [2] to remove car:");  
            //Reset of your code   
相关问题