Ho un problema nella creazione di un nuovo oggetto in modo dinamico utilizzando l'input dell'utente. So come farlo usando ArrayList ma mi stavo chiedendo se sarebbe stato possibile usare solo un array? Object 1
e Object 2
estendono da MainObject
.Creare un nuovo oggetto dall'input dell'utente usando array e non ArrayList in Java
Al momento ho:
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)
Così ho aggiunto gli oggetti nella matrice in questo modo
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;
compilato ed eseguito e funziona benissimo, ma mi dà un java.lang.NullPointerException : null e il codice evidenziato che causa il problema è
Main[x].displayComputer();
Che cos'è C qui amico? E perché hai hardcoded l'indice a 0 e 1. È un ciclo do while giusto? – SacJn