2013-04-08 5 views
0

Je veux créer un tableau 2D qui crée un mini tableau des places d'un avion. Jusqu'à présent, je l'ai réussi à imprimer quelque chose qui ressemble à ceci:Array 2D modifiable

1A (0) || 1B (0) || 1C (0)

2A (0) || 2B (0) || 2C (0)

3A (0) || 3B (0) || 3C (0)

4A (0) || 4B (0) || 4C (0)

Les zéros représentent un siège vide et le numéro un est utilisé pour représenter un siège occupé.

J'ai d'abord créé le programme avec des tableaux qui étaient des variables de classe pour une première classe, mais je voulais que ce programme soit utilisable pour une section de classe économique. La seule différence entre les deux sections est la taille du tableau, donc j'edited mon code pour ressembler à ceci:

public class Seating 
{ 
private int FIRSTCLASS= 12; 
private int ECONOMYCLASS= 240; 
private int occupied, column; 
private String[][] seatchart; 
private int[][] seatlist; 
private String[][] namelist; 
private String name; 
public String customer; 

public Seating(String seatclass) 
{ 
    seatclass.toUpperCase(); 
    if (seatclass.equals("FIRSTCLASS")) 
    { 
     seatchart= new String[FIRSTCLASS/3][3]; 
     seatlist= new int[FIRSTCLASS/3][3]; 
     namelist= new String[FIRSTCLASS/3][3]; 
    } 
    else 
    if (seatclass.equals("ECONOMY")) 
    { 
     seatchart= new String[ECONOMYCLASS/3][3]; 
     seatlist= new int[ECONOMYCLASS/3][3]; 
     namelist= new String[ECONOMYCLASS/3][3]; 
    } 

} 
public void Creation() 
{ 
    for (int i=0; i< seatlist.length; i++) 
    { 
     for (int j=0; j<seatlist[i].length; j++) 
     { 
      seatlist[i][j]= 0 ; 

     } 
    } 

Je reçois une erreur d'exception de pointeur NULL autour for (int i=0; i< seatlist.length; i++) Comment puis-je corriger cette erreur?

Merci d'avance!

Répondre

2

Le problème est avec cette ligne:

seatclass.toUpperCase(); 

Remplacez-le par:

seatclass = seatclass.toUpperCase(); 

Je pense que vous créez la classe avec une chaîne comme « première classe » plutôt que « FIRSTCLASS » droit? Ce ne sont pas les mêmes chaînes et l'invocation de la méthode toUpperCase sur la chaîne sans assigner le résultat à une variable à tester signifie que rien ne se passe.

Ensuite, comme aucune de vos conditions if n'est remplie, les tableaux ne sont pas initialisés et une exception de pointeur NULL est levée lorsque Completion() est appelée.

Je ne sais pas si vous êtes nouveau à la programmation java, mais je voulais ajouter quelques recommandations à votre classe:

public class Seating { 

private static int FIRSTCLASS= 12; // Make these constants static since they pertain to all 
private static int ECONOMYCLASS= 240; // instances of your class. That way there is exactly on 
             // copy of the variables, which is more memory efficient. 
private int occupied; 
private column; // Okay but Java convention is to declare each member variable on its own line 
        // increases code readability. 
private String[][] seatchart; 
private int[][] seatlist; 
private String[][] namelist; 
private String locSeatClass; 
private String name; 

public String customer; // Okay but better to leave this private and then provide getter and 
         // setter methods to provide access to this string. Much easier to track 
         // down who is changing its value in your code. 

public Seating(String seatclass) { // Java convention is to place the opening bracket here not 
            // on the next line. 
    // Make sure that seatClass is not null or empty. NOTE: This is a neat trick for 
    // simultaneously checking for both null and empty strings in one shot. Otherwise, you have 
    // you have to check for null and then examine the string's length which is more code. 
    if ("".equalsIgnoreCase(seatClass) { 
     throw new IllegalArgumentException("Seat class undefined."); 
    } 

    // Store the seat class in a member variable for use. Could also be a local variable. 
    // My original solution is problematic because it changes the original value of the seat 
    // class that was passed into the constructor (you might want that information). 
    locSeatClass = seatclass.toUpperCase(); 

    if (locSeatClass.equals("FIRSTCLASS")) 
    { 
     seatchart= new String[FIRSTCLASS/3][3]; 
     seatlist= new int[FIRSTCLASS/3][3]; 
     namelist= new String[FIRSTCLASS/3][3]; 
    } 
    else if (locSeatclass.equals("ECONOMY")) { 
     seatchart= new String[ECONOMYCLASS/3][3]; 
     seatlist= new int[ECONOMYCLASS/3][3]; 
     namelist= new String[ECONOMYCLASS/3][3]; 
    } 
    else { 
     // Throw an exception if someone passes in an unknown seat class string. 
     throw new IllegalArgumentException("Unknown seat class detected.") 
    } 

} 

public void creation() { // NOTE: Java convention is to begin method names with a lower 
         // case letter. 

    // This method is unnecessary. Arrays of integers are initialized with an initial value 
    // of zero by default. However, if you want to make your class reusable, you could change 
    // change the name of the this method to clear, which would allow you to clear the arrays of 
    // an existing object. 
    for (int i=0; i< seatlist.length; i++) 
    { 
     for (int j=0; j<seatlist[i].length; j++) 
     { 
      seatlist[i][j]= 0 ; 

     } 
    } 

}

+0

Merci!J'ai réalisé cela et après que je l'ai corrigé il compile et fonctionne bien :) – nichi

+0

Uhm, pas de gros problème, mais je pense que ma réponse est la réponse. M. Hopp est un bon conseil, certainement. – CBass

+0

Désolé j'ai accepté sa réponse avant que j'ai vu le vôtre! Je ne savais pas que vous pouviez changer la réponse choisie, mais je l'ai changé :) – nichi

2

La seule façon dont cette ligne de code peut générer un NPE est si seatlist est null. Sauf si vous affectez null à seatlist ailleurs dans votre classe, la seule façon de le faire est null si l'argument que vous transmettez au constructeur Seating ne correspond pas à "FIRSTCLASS" ou "ECONOMY". Vérifiez votre appel au constructeur. En outre, vous pouvez utiliser seatclass.equalsIgnoreCase().

Vous devez modifier votre constructeur pour avertir au moins cette éventualité, car il est indispensable au bon fonctionnement de la classe que toutes les instances de Seating valides ont seatlist et namelist tableaux.

+0

Je ne regardais pas à mon code attentivement et J'ai mal utilisé le .toUpperCase() dans le code. Je vais me rappeler de regarder attentivement mon code la prochaine fois .. et merci pour le conseil :) – nichi