我正在向数组中添加对象。我可以成功添加第一个对象,并循环到第二个对象。在我添加第二个对象后,当方法结束时,数组会删除第二个对象。
这是一堂课,所以我们只限于学到的基本知识。我错过了什么?
public class Assignment02Driver {
Scanner input = new Scanner(System.in);
Item yourItem = new Item();
Item[] cargohold = new Item[1];
Item[] holdThis = new Item[1];
int numberOItems = 0;
int index = 0;
public static void main(String[] args) {
new Assignment02Driver();
}
public Assignment02Driver() {
System.out.println("Welcome to the BlackStar Cargo Hold interface.");
System.out.println("Please select a number from the options below");
System.out.println("");
while (true) {
// Give the user a list of their options
System.out.println("1: Add an item to the cargo hold.");
// Get the user input
int userChoice = input.nextInt();
input.nextLine();
switch (userChoice) {
case 1:
addItem(cargohold);
break;
// Other Stuff
// Add Item Method
private void addItem(Item cargohold[]) {
Item cargo = new Item();
while (numberOItems > 10) {
System.out.println("We're too good at pirating. Go remove some loot.");
}
// Name item
System.out.println("What item did you loot?"); // Hey you!
String item = input.nextLine(); // What item was gained
cargo.setName(item); // Save in position 1 of array
// Item weight
System.out.println("What is its weight in kilograms?");
double mass = input.nextDouble();
cargo.setWeight(mass);
// Item value
// Item durability
// Item ID
我认为问题出现在这里,但我不知道如何解决它:
// Resize the array and add the item to it
if (numberOItems == cargohold.length) {
Item[] holdThis = new Item[cargohold.length + 1];
for (int i = 0; i < numberOItems; i++) {
holdThis[i] = cargohold[i];
}
cargohold = holdThis;
}
cargohold[numberOItems] = cargo;
// Add item to count
numberOItems++;
}
在它存在此方法之后,第二个项目将从数组中删除/丢失。如果我尝试添加另一个项目,我会收到一个越界错误。