Null Pointer Exception when trying to set a value - java

So pretty much I'm making an array of obvjects called Spots which symbolise the different faces of a dice.
It takes user input (manually set to three for this example), and then creates that make Spots and rolls a random number from 1 to 6.
However when I go to use the rollAgain() method on the aleady created array of Spots I get a null pointer even though I am using the same variable length in both for loops (the one that creates and one that rolls the spots).
My code
Global Variables
private Spots[] spots;
private int x = 3;
Contructor
public Director(JFrame window, String args[]) {
JMenuBar menus = new JMenuBar();
window.setJMenuBar(menus);
menus.add(makeFileMenu());
window.getContentPane().add(makePanel(), BorderLayout.WEST);
window.getContentPane().add(makeSpots(x), BorderLayout.CENTER);
rollAgain();
}
rollAgain() method
public void rollAgain() {
int v = 1 + (int) (Math.random() * 6);
for (int i = 0; i < x; i++) {
spots[i].setValue(v);
}
}
makeSpots() method
private JComponent makeSpots(int x) {
JPanel p = new JPanel();
p.setBorder(BorderFactory.createTitledBorder("Dice"));
Spots[] spots = new Spots[x];
for (int i = 0; i < x; i++) {
spots[i] = new Spots(200, 200);
spots[i].setBorder(BorderFactory.createEtchedBorder());
p.add(spots[i]);
}
return p;
}

You are setting a local variable
Spots[] spots = new Spots[x];
This doesn't change the field (which happens to have the same name)
private Spots[] spots;
The simplest solution is to not have a local variable
this.spots = new Spots[x];

You need to instantiate a new Spots array in your constructor.
this.spots = new Spots[x];

spots[i].setValue(v);
Judging from this line, my guess is that the Spot object in the array in null.
The error is in your makeSpots() method. You don't update the value of the field x, but use a local variable. Add this.x = x at the beginning of the method.

In your makeSpots() method, you are creating a new Spots object called spots:
Spots[] spots = new Spots[x];
This effectively hides your private member variable spots from the method. Instead, do this in your makeSpots() method:
spots = new Spots[x];

You are declaring a global 'spots' array and then in the makeSpots() you create the spots with a local variable also named 'spots'. Just substitute
Spots[] spots = new Spots[x];
by
spots = new Spots[x];
so the global variable gets a value.

Related

Class instance change another instance

The code is :
package classes;
public class Test {
private static double mutationRate = 0.5;
public static void main(String[] args) {
Population pop = new Population();
pop.initialise();
Population po = new Population();
po.getIndividusList().add(pop.getFittest());
po.getIndividusList().add(mutate(pop.getIndividusList().get(1)));
}
private static Chromosom mutate(Chromosom l) { // changer les couples d'interventions des parcs)
// loop through genes
Chromosom ch = new Chromosom();
for (int i = 0; i < l.size(); i++)
ch.put(i, l.get(i));
for (int i = 0; i < ch.size(); i++) {
double alea = Math.random() * 13;
int moisIntervention1 = (int) alea;
Intervention interv1 = new Intervention(1, moisIntervention1);
ch.get(i).modInterventions(ch.get(i).intervention2(interv1));
}
return ch;
}
}
The problem is that I did not change the instance pop but when I change the other instance po, pop changes too.
java pass by value.
when you call this mutate(pop.getIndividusList().get(1))
you are sending pop's instance, so it will get change.
Supose pop.getIndividusList().get(1) return String varibale do this way
String var=pop.getIndividusList().get(1);
then call mutate(var)
I'm unsure about whether I understood the problem, but I think that you mean that when you alter the items in Population po, the items in Population pop mirror those changes.
That is, indeed, the expected behavior of your code: to populate po, you are adding items from pop - (pop.getFittest, pop.getList.get(1) ).
But the individuals are, I believe, instances of objects, so add/remove and similar operations work with references to the objects, and not with copies of them. Therefore, as you have 2 references to the same obj, any change is mirrored.
IF you want to create a copy, you should add to po a new object with the same state, either by creating a constructor that takes another instance as parameter, implementing a copy method, or something similar.
It should be something like this:
Population po = new Population();
Individual fittest = pop.getFittest();
Individual poCopy = new Individual();
//ADD CODE HERE TO COPY ALL THE FIELDS FROM fittest TO poCopy
//....
po.getIndividusList().add(poCopy);

NPE when trying to access variable from a method. Processing/Java

I'm trying to make a Grid Class to use in a Sketch I want to make (I'm using Processing) but I get a NullPointerException when trying to access the grid variable from a method printGrid() of the Grid Class.
Code:
Grid_Proj:
Grid gridObj;
void setup() {
size(480, 360);
background(0);
gridObj = new Grid(10, 10);
gridObj.printGrid();
}
Grid:
class Grid {
int[][] grid; // Declare the Grid
Grid(int size_x, int size_y) {
int grid[][] = new int[size_x][size_y]; // Initialize the Grid
for (int x=0;x<size_x;x++) {
for (int y=0;y<size_y;y++) {
grid[x][y] = 0;
}
}
println("Created Grid Object with: ", size_x, size_y);
}
void printGrid() {
for (int x=0;x<10;x++) {
for (int y=0;y<10;y++) {
print(grid[x][y]); // NPE Error here
}
print('\n');
}
}
}
I'm obviously doing something wrong here, but I can't figure out what.
I also tried using
this.grid[x][y]
to no avail.
int grid[][] = new int[size_x][size_y];
You are declaring a new local grid variable here, not initializing the field. Therefore, the grid field remains null and you receive an NPE when you try to index it. Try this instead:
grid = new int[size_x][size_y]; // use the field `grid`
As an aside, it's recommended in Java to put the [] of array declarations directly after the array type:
int[][] grid // good
int grid[][] // bad
You do this correctly when declaring the field, but not in the local variable declaration.
In your constructor, you're initializing grid as a method-scoped variable, so you're never assigning any value to your instance field.
That's why you're instance method printGrid, which does reference the instance field, throws a NullPointerException.
Just remove int from the assignment in the constructor.
It's because in your constructor, you create a local grid array. Just don't create the local variable and you should be fine:
public Grid(int size_x, int size_y) {
this.grid = new int[size_x][size_y];
for (int x=0;x<size_x;x++) {
for (int y=0;y<size_y;y++) {
this.grid[x][y] = 0;
}
}
}

How do I make a value global so I can access anywhere in a class

How do I make a value global?
For example I have a few lines of code here
public class A
{
int number;
JLabel[] l = new JLabel[number]; // Problem is at here because the number
public A( int num )
{
number = num; // Receive the value from previous file
}
}
Problem is at the line where I state in the commnet.
As far as I know, the number doesn't passed on to creation of JLabel. Is there anyway for me to pass the value taken from previous file to the creation of JLabel?
I need to create the JLabel globally because I need to access it at the public void actionPerformed(ActionEvent e).
If I create it inside the method I couldn't access at the public void actionPerformed(ActionEvent e) or is there anyway I could access the JLabel I creatd in a method?
Just leave the top line as JLabel[] l; and add l = new JLabel[number]; in your constructor. The problem is that your code as is will try to access number before calling the constructor, so it is not yet set.
When you are creating your class, you declare int variable, which is not initialised, and then you go on to create JLabel array using this variable. To solve this, you can initialize number in your constructor, and also there, create your JLabel, like so:
public class A
{
int number;
JLabel[] l;
public A( int num )
{
number = num; // Receive the value from previous file
l = new JLabel[number]
}
}

Initialising/Creating Objects through a constructor

Ok so I'm doing an assignment for my java coursets part I'm stuck at is :
"Implement an operation createparliamentMembers which will create the particular Parliament
with 80 members."
So i've already created the constructor with it's methods. This is how I wrote the operation to create the objects using the constructor.:
public static void createparliamentMembers(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
The problem is the arrays and objects only seem to exist in the operation for creating them and when I try running method of the objects created they don't work because the driver class doesn't recognize the arrays. On the other hand when I use this as just a normal part of the Driver for it runs fine and all methods of the objects work normally.
Edit: Ok so I'm still getting the same problem as before even though i initiliased them outside the createparliamentMembers();
The following code is the Driver im using to test the methods: It keeps saying there is a:
Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:11)
which is the code array[1].FlipCoin(); as im trying to use the method flipcoin from the created objects but it's not working.
public static void main(String [] args) {
Commands.createparliamentMembers();
array[1].FlipCoin();
}
Your arrays are only defined locally, which means they live and die with the method. When your method finishes, they get put out of memory.
The solution is to define these arrays as instance variables. By that I mean, you need to define the arrays for your class, and then use them in your method:
class someClass {
int[] myArray = new int[2];
private void someMethod() {
myArray[0] = 3;
myArray[1] = //whatever
}
}
You state in comment:
I do have a parliament class it's on it own and contains the methods and constructor for the members of the parliament. The above method was in a seprate class called Commands. I don't understand completely the "Can you add the members to a Parliament object as you create them?" The parliament isn't an object more se then a class containing a constructor and methods for parliament members i want to create.
Parliament isn't an object yet, but you should in fact create one, and in fact your instructions tell you just that: "which will create the particular Parliament with 80 members...". You will need to tell us more about your program's structure and your specific requirements, but I suggest:
First create a Parliament object in the createParliamentMembers method, and call it parliament.
Then create the members of parliament in that method.
As you create these members, add them to the Parliament object, parliament.
At the end of the method return the parliament variable.
This means that your createParliamentMembers method's signature must change so that rather than return void it should be written to return a Parliament object.
When calling the method in the main method, assign what it returns to a Parliament variable that is in the main method.
It looks like you are writing a factory method. Create a constructor for Parliament like this:
public Parliament(Member[] members, Legislator[] legislators, Leader[] leaders) {
// do whatever with what's passed in
}
Then change your method to return a Parliament object and in the method pass your initialized arrays into the Parliament constructor, like this:
// same code as your except the last line
public static Parliament createParliament(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
return new Parliament(array, leg, lead);
}

Copying an object using a constructor, Java

So lets say I want to make a deep copy of an object, but using its contsructor. So I have:
public class PositionList {
private Position[] data = new Position[0];
private int size = 0;
public PositionList(PositionList other, boolean deepCopy) {
if (deepCopy==true){
size=other.getSize();
for (int i=0;i<data.length;i++)
data[i]=other.data[i];
}
else {
data=other.data;
size = other.size;
And so say I have this being called:
PositionList list = new PositionList();
PositionList acopy = new PositionList(list, true);
What I am doing, however, is incorrect, and Im not sure why..
The problem lies in your deep copy logic:
size=other.getSize();
for (int i=0;i<data.length;i++)
data[i]=other.data[i];
You are setting the size field (which is redundant with the data array) but are not assigning a new array to the data field, which is presumably the whole point of your "deep" copy. You should initialize data to the other's size (or other.data.length):
data = new Position[other.data.length];
for (int i=0;i<data.length;i++)
data[i]=other.data[i];
(And get rid of size all together)

Categories