Hi there! I've been struggling trying to create a simulation based off of Thomas Schelling's segregation model for a while now. I thought I'd finally sussed out how to calculate the neighbours and compare them, but I get a nullpointer exception in the comparison line of code (line 66). Below is my code for the red colour I need to move - both the total number of red neighbours and the total number of all neighbours return the correct value.
Any help is appreciated!
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
* Write a description of class Red here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Red extends Actor
{
private double happyLevel;
public boolean happy = false;
private int x;
private int y;
public List rneighbours;
public List neighbours;
public Red()
{
GreenfootImage image = getImage();
image.scale((image.getWidth() - image.getWidth() + 10), (image.getHeight() - image.getHeight() + 10));
setImage(image);
}
/**
* Act - do whatever the Red wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
checkhappy();
move();
}
public void findEmptyCell()
{
x = Greenfoot.getRandomNumber(getWorld().getWidth());
y = Greenfoot.getRandomNumber(getWorld().getHeight());
while (isOccupied(x, y) == true)
{
x = Greenfoot.getRandomNumber(getWorld().getWidth());
y = Greenfoot.getRandomNumber(getWorld().getHeight());
}
}
public boolean isOccupied(int x, int y)
{
return ! getWorld().getObjectsAt(x, y, null).isEmpty();
}
public int getredNeighbours()
{
List rneighbours = getNeighbours(1, true, Red.class);
return rneighbours.size();
}
public int getallNeighbours()
{
List neighbours = getNeighbours(1, true, null);
return neighbours.size();
}
public boolean checkhappy()
{
happyLevel = 0.5;
getredNeighbours();
getallNeighbours();
if (rneighbours.size() >= (happyLevel * neighbours.size()))
{
happy = true;
}
else
{
happy = false;
}
return happy;
}
public void move()
{
if (happy == false)
{
findEmptyCell();
setLocation(x, y);
}
}
}
