I need to write code that moves a point in a grid, by adding or subtracting a number. The code works while the parameter n is 5 digits and print the correct answers. When I make it bigger (and still inside the integers interval), it gives me the heap space error.
This is the code.
import java.util.*;
import java.awt.Point;
public class Particles {
public static void main(String[] args) {
runSimulation(11234234, 132423, 50);
}
public static void runSimulation(int n, int s, int t) {
// tre punkt objekter dannes
Point P1 = new Point();
Point P2 = new Point();
Point P3 = new Point();
System.out.println("n=" + n + " s=" + s + " t=" + t);
// n x n griddet, repræsenteres ved et to dimensionelt array
int grid[][] = new int[n][n];
// punkter tildeles til at starte en tilfældig placering i griddet
P1.x = new Random().nextInt(grid.length);
P1.y = new Random().nextInt(grid.length);
P2.x = new Random().nextInt(grid.length);
P2.y = new Random().nextInt(grid.length);
P3.x = new Random().nextInt(grid.length);
P3.y = new Random().nextInt(grid.length);
System.out.println("move " + 1 + ", positions P1=" + "[" + P1.x + ";" + P1.y + "]" + " P2="
+ "[" + P2.x + ";" + P2.y + "]" + " P3=" + "[" + P3.x + ";" + P3.y + "]");
// for løkken udfører bevægelserne baseret på argumentet t for metoden
for (int i = 2; i <= t; i++) {
Random random = new Random();
int range = random.nextInt((s + 1) + s) - s;
P1.x += range;
P1.y += range;
P2.x += range;
P2.y += range;
P3.x += range;
P3.y += range;
// if sætninger for at gøre rede for at flytte en partikel ind i den nærmeste plads i griddet, hvis partiklen er uden for griddet.
if (P1.x > n-1) {
P1.x = n-1;
}
if (P1.x < 0) {
P1.x = 0;
}
if (P2.x > n-1) {
P2.x = n-1;
}
if (P2.x < 0) {
P2.x = 0;
}
if (P3.x > n-1) {
P3.x = n-1;
}
if (P3.x < 0) {
P3.x = 0;
}
if (P1.y > n-1) {
P1.y = n-1;
}
if (P1.y < 0) {
P1.y = 0;
}
if (P2.y > n-1) {
P2.y = n-1;
}
if (P2.y < 0) {
P2.y = 0;
}
if (P3.y > n-1) {
P3.y = n-1;
}
if (P3.y < 0) {
P3.y = 0;
}
System.out.println("move " + i + ", positions P1=" + "[" + P1.x + ";" + P1.y + "]" + " P2="
+ "[" + P2.x + ";" + P2.y + "]" + " P3=" + "[" + P3.x + ";" + P3.y + "]");
}
}
}
And the error I get is this
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at testpackingheat.Particles.runSimulation(Particles.java:22)
at testpackingheat.Particles.main(Particles.java:9)
This comes from when the grid size is too big, and I have tried allocating more RAM and run it, but the same error comes out.