用户最初需要选择选项“a”来添加最终放置衣服的衣柜位置。他们的信息被放入arraylist而不会被覆盖。这部分有效。
然后他们可以选择选项b,在那里它根据楼层号搜索arraylist的位置。如果找到楼层号,则用户输入装备类型,然后将其发送到Location类中的arraylist。这就是我被困住的地方。它似乎将它添加到arraylist,但是如果我想回去为该楼层号的衣柜位置添加另一套装,它会覆盖它而不是添加它。
我需要它能够将用户的装备添加到arraylist并允许用户返回,为选项b输入相同的楼层编号,并添加另外的装备以及添加的初始装备(并且不覆盖)。
我的代码如下。
主要方法:
public class Main {
public static void main(String[] args) {
int selection;
Scanner console = new Scanner(System.in);
String firstInput;
int floorNumber;
String roomLocation;
boolean loop;
boolean bigLoop;
ArrayList<Location> locationArr = new ArrayList<Location>();
do{
bigLoop = true;
do{
loop = true;
System.out.println("Select from the following:");
System.out.println("a. Add wardrobe location");
System.out.println("b. Add outfit to the wardrobe location");
firstInput = console.nextLine();
if (firstInput.equals("a")) {
System.out.println("Please enter which floor your wardrobe is located on:");
floorNumber = console.nextInt();
console.nextLine();
System.out.println("Please enter room your wardrobe is located in (e.g. living room, bedroom, etc.):");
roomLocation = console.nextLine();
Location currLocation = new Location(floorNumber, roomLocation);
locationArr.add(currLocation);
}
if (firstInput.equals("b")){
loop = false;}
} while (loop == true);
do {
loop = true;
String outfitType;
System.out.println("Please enter the floor number:");
floorNumber = console.nextInt();
console.nextLine();
for (int i = 0; i < locationArr.size(); i++){
if (locationArr.get(i).getFloorNumber() == floorNumber) {
Location currLocation = new Location(locationArr.get(i).getFloorNumber(),locationArr.get(i).getRoomLocation());
i = locationArr.size();
System.out.println("Please enter the type of outfit to put in the wardrobe (e.g. dress, suit, etc.):");
outfitType = console.nextLine();
String newOutfit = outfitType;
currLocation.addOutfit(newOutfit);
loop = false;
}
}
} while (loop == true);
} while (bigLoop == true);
}
}
位置等级
public class Location {
private final int flooorNumber;
private final String rooomLocation;
private final ArrayList<String> clothesInWardrobe = new ArrayList<String>();
public Location(int floorNumber, String roomLocation) {
this.flooorNumber = floorNumber;
this.rooomLocation = roomLocation;
}
public int getFloorNumber(){
return flooorNumber;
}
public String getRoomLocation(){
return rooomLocation;
}
public int addOutfit(String outfit){
clothesInWardrobe.add(outfit);
//the next two lines just test to see if it adds to or overwrites the arraylist
for (String testToSeeIfItWorks : clothesInWardrobe) {
System.out.println("In Wardrobe = " + testToSeeIfItWorks);}
return clothesInWardrobe.size();
}
}
答案 0 :(得分:1)
您的问题是您正在i位置创建位置的新实例。
Location currLocation = new Location(locationArr.get(i).getFloorNumber(),locationArr.get(i).getroomLocation(),locationArr.get(i).getWardrobeLocation());
由于您没有将旧衣柜传递到该位置,因此正在创建衣柜的新ArrayList。 您应该使用现有位置而不是创建新位置。
Location currLocation = locationArr.get(i);