我在使用用户输入动态创建新对象时遇到问题。我知道如何使用 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();
最佳答案
ArrayList
可以具有可变大小,而数组是静态大小。也就是说,一旦你分配了一个数组,你就不能追加/插入新元素。但是,您可以分配一个大数组,然后逐个填充它。一般来说,这个过程是这样的:
int nextSpot = 0; //next spot to fill in array
while (still_getting_input) {
if (supposed_to_insert) {
if (nextSpot_in_valid_range)
myArray[nextSpot++] = value_to_insert;
else
System.out.println("Invalid operation!"); //cannot insert.
}
}
所以,你的程序应该是这样的:
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^
String input;
Scanner scanner = new Scanner(System.in);
int nextSpot = 0;
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 :
if (nextSpot < Main.length) {
object1 obj1 = new object1();
System.out.println("Please enter name of object: ");
obj1.setName(scanner.nextLine());
obj1.display();
Main[nextSpot++] = obj1;
}
else {
System.out.println("Error!");
}
break;
// etc.
}
}
while (input==1 || input==2 || input==3)
您的代码还有一些其他问题(特别是您对 switch
语句的使用;您将遇到失败),但这回答了您提出的问题。
关于java - 使用数组而不是 Java 中的 ArrayList 从用户输入创建一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131948/