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