【问题标题】:Create a new object from user input using array and not ArrayList in Java使用数组而不是 Java 中的 ArrayList 从用户输入创建一个新对象
【发布时间】:2023-03-05 13:49:01
【问题描述】:

我在使用用户输入动态创建新对象时遇到问题。我知道如何使用 ArrayList 来做到这一点,但我想知道是否可以只使用一个数组? Object 1Object 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


【解决方案1】:

你的问题其实是array和arraylist在被迭代的时候,要走多久?

当你迭代数组时,它的正常迭代会达到你在初始化时为数组声明的大小。但是对于arrayList,它是arrayList中实际存在多少元素。在默认容量后,arrayList 在内部会根据需要将其大小翻倍。

您可以跟踪要添加到其中的元素数量。 或者只是对索引元素执行 NULL POINTER CHECK

【讨论】:

    【解决方案2】:

    ArrayLists 可以具有可变大小,而数组具有静态大小。也就是说,一旦分配了一个数组,就不能追加/插入新元素。但是,您可以分配一个大数组,然后逐个填充它。总的来说,这个过程是这样的:

    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.lang.NULLPointerException:null 错误。我的案例 3 有问题
    • @GabrielChan 您不想遍历整个数组长度,而只想遍历您已填充的部分。换句话说,只有当你的迭代器小于nextSpot
    • @Gabriel Chan,原因是 array.length 将返回 99 但您只设置了第 0 个和第 1 个索引。所以在两次迭代之后,它会抛出空指针异常,因为你只为数组分配了内存,但从未将它们全部设置为默认的非空值。
    • @GabrielChan 它适用于 arrayList,因为 arrayList 的大小仅限于您添加的内容。所以你的循环不会超出这个范围
    • @SacJn 我知道它适用于arraylist,但我试图只使用array。如果我想让 case 3 的循环立即停止,它已经显示了所有分配的内存,我应该怎么做。
    【解决方案3】:

    我会做这样的事情,

    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)
    

    【讨论】:

      【解决方案4】:

      请注意,您错过了将值加载到 Main[] 数组中,因为只有对象 obj1(以及类似的 obj2 ...)被初始化。维护一个索引并将对象相应地添加到数组中:

      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))
      

      【讨论】:

        猜你喜欢
        • 2017-04-23
        • 2015-11-11
        • 2015-11-13
        • 2016-01-10
        • 2016-11-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 1970-01-01
        相关资源
        最近更新 更多