Reputation: 68
I just started with Java. I'm trying to make a simple (almost Hello world) program:
The player class is called "Jugador". I get a NullPointerException error. I more or less understand the concept, but I still have no idea why it isn't working =(. Any help is appreciated.
Source:
Chicago2.java:
package chicago2;
import javax.swing.JOptionPane;
public class Chicago2 {
public static void main(String[] args) {
String s;
Jugador jugadores[];
jugadores=new Jugador[3];
int i=1;
System.out.println("Loading players:");
for(Jugador x: jugadores) {
s=JOptionPane.showInputDialog("Name of player "+i+": ");
x = new Jugador(s);
System.out.println("Player "+i+": "+x.getName());
i++;
}
System.out.println("Printing players name:");
for(Jugador y : jugadores) {
System.out.println("Plays: "+y.getName());
}
}
}
Jugador.java:
package chicago2;
public class Jugador {
private String name;
public Jugador(String nom)
{
name=nom;
}
public String getName() {
return name;
}
}
Error I get (Output):
run:
Loading players:
Player 1: a
Player 2: b
Player 3: c
Printing players name:
Exception in thread "main" java.lang.NullPointerException
at chicago2.Chicago2.main(Chicago2.java:19)
Java Result: 1
Line 19 is:
System.out.println("Plays: "+y.getName());
Work environment:
Product Version: NetBeans IDE 7.3 (Build 201302132200)
Java: 1.7.0_17; Java HotSpot(TM) 64-Bit Server VM 23.7-b01
Runtime: Java(TM) SE Runtime Environment 1.7.0_17-b02
System: Linux version 2.6.32-41-generic running on amd64; UTF-8; en_US (nb)
Screenshot:
If you read this far, thank you.
Upvotes: 0
Views: 140
Reputation: 45080
The names you're getting from user are not being stored in your array. You need to do that this way:-
x = new Jugador(s);
jugadores[i] = x;
Also, the int i=1;
should be int i=0;
.
But for better readability, see the below code changes:-
System.out.println("Loading players:");
for(int i = 0; i < jugadores.length; i++) { // Better readability.
s=JOptionPane.showInputDialog("Name of player "+i+": ");
Jugador x = new Jugador(s);
jugadores[i] = x; // Added
System.out.println("Player "+i+": "+x.getName());
}
Upvotes: 2
Reputation: 5919
You are not really storing anything in jugadores
.
To store, replace the line x = new Jugador(s);
with x = jugadores[i-1] =new Jugador(s);
Upvotes: 0