【发布时间】:2023-03-05 13:49:01
【问题描述】:
我在使用用户输入动态创建新对象时遇到问题。我知道如何使用 ArrayList 来做到这一点,但我想知道是否可以只使用一个数组? Object 1 和 Object 2 扩展自 MainObject。
我目前有:
import java.util.Scanner;
public class Main
{
public static void main (String args[])
{
MainObject[] Main = new MainObject[99];
//^objects created will be added to this array^
int input;
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("1. Add a new object 1");
System.out.println("2. Add a new object 2");
System.out.println("3. Display all object info");
System.out.println("4. Quit");
System.out.print("Please enter either 1 to 4: ");
input =(scanner.nextLine());
switch(input) {
case 1 :
object1 obj1 = new object1();
System.out.println("Please enter name of object: ");
obj1.setName(scanner.nextLine());
obj1.display();
case 2 :
object2 obj2 = new object2();
System.out.println("Please enter name of object: ");
obj2.setName(scanner.nextLine());
obj2.display();
case 3 :
//this is where the for loop should be to display all the info of obj 1 and 2
case 4 :
System.out.println("Thank You");
break;
}
}
while (input==1 || input==2 || input==3)
所以我像这样将对象添加到数组中
case 1 :
object1 obj1 = new object1();
System.out.println("Please enter name of object: ");
obj1.setName(scanner.nextLine());
obj1.display();
Main[0] = obj1;
break;
case 2 :
object2 obj2 = new object2();
System.out.println("Please enter name of object: ");
obj2.setName(scanner.nextLine());
obj2.display();
Main[1] = obj2;
break;
case 3 :
int x = 0;
for (x=0; x<Main.length; x++)
{
Main[x].displayComputer();
}
break;
编译并运行,它工作正常,但它给了我一个 java.lang.NULLPointerException:null 并且导致问题的突出显示的代码是
Main[x].displayComputer();
【问题讨论】:
-
这里的C是什么哥们?为什么要将索引硬编码为 0 和 1。它是一个 do while 循环吗?
标签: java arrays loops arraylist