简体   繁体   English

使用数组而不是使用Java中的ArrayList从用户输入创建新对象

[英]Create a new object from user input using array and not ArrayList in Java

I've a problem creating a new object dynamically using the user input. 我在使用用户输入动态创建新对象时遇到问题。 I know how to do it using ArrayList but I was wondering if it would be possible to use only one array? 我知道如何使用ArrayList,但我想知道是否可以只使用一个数组? Object 1 and Object 2 extend from MainObject . Object 1Object 2MainObject扩展。

I currently have: 我目前有:

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)

So I have added the objects into the array like so 所以我已经将对象添加到数组中了

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;

Compiled and run and it works fine but it gives me a java.lang.NULLPointerException:null and the highlighted code that causes the problem is 编译并运行它工作正常,但它给了我一个java.lang.NULLPointerException:null和导致问题的突出显示的代码是

Main[x].displayComputer();

ArrayList s can have variable size, while an array is of static size. ArrayList可以具有可变大小,而数组具有静态大小。 That is, once you allocate an array, you cannot append/insert new elements. 也就是说,一旦分配了数组,就无法追加/插入新元素。 However, you can allocate a large array, then fill it in piece-by-piece. 但是,您可以分配一个大型数组,然后逐个填充它。 In general, the process looks like this: 通常,该过程如下所示:

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.
    }
}

So, your program would look like: 所以,你的程序看起来像:

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)

There are some other problems with your code (particularly, your usage of a switch statement; you're going to experience fall-through), but this answers the question you asked. 您的代码还有一些其他问题(特别是您使用switch语句;您将体验到堕落),但这会回答您提出的问题。

I would do something like this, 我会做这样的事,

int index = 0;

do {
   ...

    case 1 :
        ...
        Main[index++] = obj1;
        break;

    case 2 : 
        ...
        Main[index++] = obj2;
        break;

    case 3:
        // Iterate over the loop till index
} while ((index < Main.length && (input==1 || input==2)) || input==3)

Your question is actually array and arraylist when being iterated, how long do they go ? 你的问题实际上是迭代时的数组和arraylist,它们需要多长时间?

When you iterate over array, its normal iteration goes to size you have declared for the array at the initialization time. 当您遍历数组时,它的正常迭代将达到您在初始化时为数组声明的大小。 But for arrayList, it is that how many elements are actually present in arrayList. 但是对于arrayList,它是在arrayList中实际存在多少个元素。 Internally arrayList doubles its size when ever it wants after a default capacity. 在默认容量之后,内部arrayList在需要时将其大小加倍。

You can rather keep a track of number of elements you are adding to it . 您可以更好地跟踪要添加到其中的元素数量 Or just do a NULL POINTER CHECK on the indexed element 或者只对索引元素执行NULL POINTER CHECK

Please note that you missed out loading the values into the Main[] array since only the object obj1 (and similarly obj2 ...) is initialized. 请注意,您错过了将值加载到Main[]数组中,因为只初始化了对象obj1 (以及类似的obj2 ...)。 Maintain an index and add the objects accordingly to the array: 维护索引并相应地将对象添加到数组:

int index=0;
...
case 1 :
    object1 obj1 = new object1();
    System.out.println("Please enter name of object: ");
    obj1.setName(scanner.nextLine());
    obj1.display();
    Main[index++] = obj1;
...
while((index < 100 && (input==1 || input==2 || input==3))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM