简体   繁体   中英

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? Object 1 and Object 2 extend from MainObject .

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

Main[x].displayComputer();

ArrayList s can have variable size, while an array is of static size. 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.

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 ?

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. Internally arrayList doubles its size when ever it wants after a default capacity.

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

Please note that you missed out loading the values into the Main[] array since only the object obj1 (and similarly obj2 ...) is initialized. 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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