0

First of all, thank you for taking the time to read!

So, I created a superclass called Phone and made three subclasses LG, Samsung and Huawei. I was trying to do this MVC-style so I went to the controller package to test out my code, imported all created classes so I could instantiate them with entering a String which would specify what subclass to create (did this using a switch). After running the program and entering names correctly, I got a NullReference. I opened debug and found that 'p', the variable used to loop, never got instantiated.

How comes? Any help is greatly appreciated!

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Phone[] phones = new Phone[3];
    for(Phone p : phones){
        System.out.println("What brand?");
        String inputBrand = scan.nextLine();
        switch(inputBrand) {
        case "LG" : p = new LG();
            break;
        case "Samsung" : p = new Samsung();
            break;
        case "Huawei" : p = new Huawei();
            break;
        default : System.out.println("You're an idiot");
            break;
        }
    }
    for(Phone p : phones){
        System.out.println(p.toString());
    }
    scan.close();
}

2 Answers2

0

That line instantiates the array, but doesn't instantiate its contents:

Phone[] phones = new Phone[3];

Foreach you're using is based on iterator, which checks content of the array, and not its size, as you expect.

p = new LG()

This line assigns new LG() to a temporary variable which is scoped inside the loop, and not to phones[i], as your intention was.

I would suggest to use List for storing your objects:

private static final int LOOPS = 3;

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<Phone> phones = new ArrayList<>();
    for(int i = 0; i < LOOPS; i++){
        System.out.println("What brand?");
        String inputBrand = scan.nextLine();
        switch(inputBrand) {
            case "LG" : phones.add(new LG());
                break;
            case "Samsung" : phones.add(new Samsung());
                break;
            case "Huawei" :  phones.add(new Huawei());
                break;
            default : System.out.println("Your code is less than optimal");
                break;
        }
    }
    for(Phone p : phones){
        System.out.println(p.toString());
    }
    scan.close();
}
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
0

You should do instead :

    for (int i = 0; i < phones.length; i++) {

        System.out.println("What brand?");
        String inputBrand = scan.nextLine();
        switch (inputBrand) {
        case "LG":
        phones[i] = new LG();
        break;
        etc etc

because so you can access the element of the array, in the other case you are setting a copy of the phone, leaving the array intact as it was declared... therfore the NPE

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97