2015-08-21 11 views
5

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

Che cos'è C qui amico? E perché hai hardcoded l'indice a 0 e 1. È un ciclo do while giusto? – SacJn

risposta

5

ArrayList s possono avere dimensioni variabili, mentre un array è di dimensione statica. Cioè, una volta assegnato un array, non è possibile aggiungere/inserire nuovi elementi. Tuttavia, è possibile allocare un array di grandi dimensioni, quindi riempirlo pezzo per pezzo. In generale, il processo è simile al seguente:

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

Quindi, il programma sarà simile:

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) 

Ci sono alcuni altri problemi con il codice (in particolare, l'utilizzo di una dichiarazione switch; voi sperimenterete fall-through), ma questo risponde alla domanda che avete posto.

+0

Ho provato il tuo metodo e ottengo ancora java.lang.NULLPointerException: errore nullo. C'è qualcosa di sbagliato nel mio caso 3 –

+0

@GabrielChan non si desidera eseguire il loop sull'intera lunghezza dell'array, ma solo sulle parti che si sono riempite. In altre parole, solo quando il tuo iteratore è inferiore a 'nextSpot'. – apnorton

+1

@Gabriel Chan, la ragione è che array.length restituirà 99 ma hai impostato solo il primo e il terzo indice.Quindi, dopo due iterazioni, genererà un'eccezione di puntatore nullo perché la memoria allocata per la matrice è stata solo assegnata, ma non è mai stata impostata su un valore non nullo, che è l'impostazione predefinita. – SacJn

0

Si prega di notare che hai perso il caricamento dei valori nell'array Main[] poiché solo l'oggetto obj1 (e allo stesso modo obj2 ...) è inizializzato. Mantenere un indice e aggiungere gli oggetti di conseguenza alla matrice:

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

vorrei fare qualcosa di simile,

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

La tua domanda è in realtà array e arraylist quando viene iterata, per quanto tempo vanno?

Quando si esegue un iterazione su un array, la sua iterazione normale va alla dimensione dichiarata per l'array al momento di inizializzazione. Ma per arrayList, è il numero di elementi effettivamente presenti in arrayList. Internamente arrayList raddoppia le sue dimensioni quando lo desidera dopo una capacità predefinita.

È possibile invece mantenere una traccia di numero di elementi che si sta aggiungendo ad esso. Oppure basta fare un CONTROLLO NULL POINTER sull'elemento indicizzato

Problemi correlati