Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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();
share|improve this question
    
What is C here buddy ? And why have you hardcoded the index to 0 and 1. Its a do while loop right ? – SacJn Aug 21 at 4:01

4 Answers 4

up vote 4 down vote accepted

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

share|improve this answer
    
I've tried your method and I still get the java.lang.NULLPointerException:null error. There is something wrong with my case 3 – Gabriel Chan Aug 21 at 4:13
    
@GabrielChan you don't want to loop over the entire array length, but only the parts you've filled. In other words, only when your iterator is less than nextSpot. – apnorton Aug 21 at 4:17
1  
@Gabriel Chan, Reason is that array.length will return 99 but you have set only 0th and 1st index. So after two iteration, it will throw null pointer exception because you have only allocated memory for array but never set all of them to non null value which is by default. – SacJn Aug 21 at 4:20
1  
@GabrielChan it works with arrayList because size of arrayList is limited to what you add to it. So your loop won't iterate beyond that – SacJn Aug 21 at 4:39
    
@SacJn I know it works with arraylist but I am trying to use just array. And if I want the loop for case 3 to stop at once it has displayed all the allocated memory how should I do it. – Gabriel Chan Aug 21 at 4:44

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)
share|improve this answer

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

share|improve this answer

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))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.