NullPointerException when using 2D array - java

My goal is to traverse a maze using a stack, but I am unable to get very far.
I have a 2D array of Room objects and I always start at position 1,1. I believe I have everything set up correctly. However, I keep getting a NullPointerException whenever I try to access the data stored in my array.
Any assistance that will point me in the right direction would be appreciated.
Here is my room class:
import java.awt.Point;
public class Room {
private Room up;
private Room down;
private Room left;
private Room right;
private char value;
private boolean blocked;
private boolean visited = false;
private Point p;
public void setCord(int row, int column) {
p = new Point(row, column);
}
public void setUp(Room [][] r, int row, int column) {
up = r[row][column];
}
public void setDown(Room[][] r, int row, int column) {
down = r[row][column];
}
public void setRight(Room[][] r, int row, int column) {
right = r[row][column];
}
public void setLeft(Room[][] r, int row, int column) {
left = r[row][column];
}
public void setValue(char c) {
value = c;
}
public void setVisited(boolean b) {
visited = b;
}
public void setBlocked(boolean b) {
blocked = b;
}
public Point getCord() {
return p;
}
public Room getUp() {
return up;
}
public Room getDown() {
return down;
}
public Room getRight() {
return right;
}
public Room getLeft() {
return left;
}
public char getValue() {
return value;
}
public boolean getVisited() {
return visited;
}
public boolean getBlocked() {
return blocked;
}
}
Here is my maze class:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.JOptionPane;
public class Maze {
String inFile, // Name of file to be used as input
outFile, // Name of file to output completed maze to
line; // Current line being read by scanner
char [][] mazeContent;
Room [][] rooms;// Holds the values that create maze
Room [] theStack;
Room current = new Room();
ArrayList<Room> al;
int rows, columns;
int tos = 0;
char [][] mazeC;
public static void main(String []args) throws Exception {
Maze m = new Maze();
}
public Maze() throws FileNotFoundException {
// Prompts user for the name of the file they wish to use as the input file.
inFile = JOptionPane.showInputDialog(null, "Please enter the name of the file you wish to read, including " +
"the file path:");
//if(inFile.equals("")) inFile = "C:\Java\JavaFiles\maze1.txt;
// Prompts user to enter the name they wish to save the file under.
outFile = JOptionPane.showInputDialog(null, "Please enter the filename you wish to save the data to:");
// Creates a scanner object to read in the input file.
Scanner readFile = new Scanner(new FileReader(inFile));
PrintWriter output = new PrintWriter(outFile);
rows = readFile.nextInt();
columns = readFile.nextInt();
readFile.nextLine();
theStack = new Room[1000];
mazeContent = new char [rows][columns];
rooms = new Room [rows][columns];
theStack = new Room[1000];
for(int i = 0; i < rows; i++) {
line = readFile.nextLine();
for(int j = 0; j< line.length(); j++) {
mazeContent[i][j] = line.charAt(j);
}
}
createRooms();
findPath();
}
private void findPath() {
Room start = rooms[1][1];
push(start);
while(!isEmpty()) {
current = pop();
//System.out.println("The value is " + current.getValue());
if(current.getValue() == '$') {
System.out.println("Success");
}
else if(current.getBlocked() != true && current.getVisited() != true) {
current.setVisited(true);
push(current.getRight());
push(current.getLeft());
push(current.getUp());
push(current.getDown());
}
}
}
public void createRooms() {
for(int i = 1; i < rows - 1; i++) {
for(int j = 1; j < columns -1; j++) {
Room r = new Room();
r.setCord(i,j);
r.setValue(mazeContent[i][j]);
r.setUp(rooms, i-1, j);
r.setDown(rooms, i+1, j);
r.setRight(rooms, i, j+1);
r.setLeft(rooms, i, j-1);
if(mazeContent[i][j] == '*')
r.setBlocked(true);
else
r.setBlocked(false);
rooms[i][j] = r;
}
}
}
private Room pop() {
return theStack[--tos];
}
private boolean isEmpty() {
// TODO Auto-generated method stub
return tos == 0;
}
private void push(Room item) {
if (isFull()) {
System.out.println("The stack is full!");
}
else
theStack[tos++] = item;
}
private boolean isFull() {
return tos == theStack.length-1;
}
}

The most likely root cause of your NullPointerException is that you have not (fully) initialized something. Perhaps a field of one of your objects. Perhaps an element of on of your arrays. When you then try to use this uninitialized field or array element, you are actually trying to perform an operation on a null reference ... and that causes the exception.
If the exception is being thrown by
if(current.getValue() == '$')
then that means that current is null. That means that you "popped" a null from your stack. On first sight, the implementations of your stack operations look OK, so my guess is that somewhere you have pushed a null.
My suggestion is to add a test in the push method that throws an exception if you attempt to push null. (Or try and track this down using a debugger.) Then continue working backwards to figure out where the null came from.

Related

Java - create 2 different matrices with same variables

I'm currently working on a version of Conway's Game of Life with Netbeans IDE and I wanted to store cells in a matrix. For the operation of going to the Next generation of cells, I would return a new matrix of cells which is calculated from the inputting matrix.
The Code is the following:
public static Cell[][] nextGen(Cell[][] CellList)
{
Cell[][] Copy = CellList.clone();
for (int i = 0; i<Copy.length; i++)
{
for(int n = 0; n<Copy[i].length; n++)
{
if (Copy[i][n].isAlive())
{
if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4 )
{
CellList[i][n].kill();
}
}else
{
if (Cell.count(Copy, i, n) == 3)
{
CellList[i][n].born();
}
}
}
}
return CellList;
}
The Class is called "Cell"
it has a private boolean property "alive" which can be set to false with the public method kill() or true with the public method born(). Everything except the method for counting alive cells surrounding a specific cell and the method for calculating the new generation is nonstatic.
The Problem why it isn't working is that if I make any changes to the input matrix "CellList", the same thing happens in the copy of this matrix.
How can I let the copy have the same Values but only make changes in the input matrix?
Thanks for the helping!
What you are doing is shallow copy, what you need is deep copy. Try this
public class Cell {
boolean alive = false;
protected Cell clone() {
return new Cell(this);
}
public Cell() {
}
public Cell(Cell cell) {
this.alive = cell.alive;
}
boolean isAlive() {
return alive;
}
void kill() {
alive = false;
}
void born() {
alive = true;
}
static int count(Cell[][] cell, int j, int k) {
return 1;
}
public static void main(String[] args) {
Cell[][] CellList = new Cell[2][3];
CellList[0][1] = new Cell();
nextGen(CellList);
}
public static Cell[][] nextGen(Cell[][] CellList) {
Cell[][] Copy = deepArrayCopy(CellList);
for (int i = 0; i < Copy.length; i++) {
for (int n = 0; n < Copy[i].length; n++) {
if (Copy[i][n].isAlive()) {
if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4) {
CellList[i][n].kill();
}
} else {
if (Cell.count(Copy, i, n) == 3) {
CellList[i][n].born();
}
}
}
}
return CellList;
}
public static Cell[][] deepArrayCopy(Cell[][] celllist) {
Cell[][] copy = new Cell[celllist.length][celllist[0].length];
for (int i = 0; i < celllist.length; i++) {
for (int k = 0; k < celllist[i].length; k++) {
if (celllist[i][k] != null)
copy[i][k] = celllist[i][k].clone();
}
}
return copy;
}
}

2-D Maze Solver: Final Maze Won't Print

I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but when I run it and enter the starting position, the final maze doesn't print out.
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
//solveStack(maze);
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for
printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++)
{ //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing
values of maze
}
System.out.println(); // new line
}
}
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void restore(String[][] savedMaze) {
for (int i=0; i< ROW; i++)
for (int j=0; j<COLUMN; j++)
maze[i][j] = savedMaze[i][j];
}
public MazeGenerator clone(MazeGenerator m) {
MazeGenerator maze = new MazeGenerator();
maze = m;
return maze;
}
//**************************************************
//this solution uses a stack to keep track of possible
//states/positions to explore; it marks the maze to remember the
//positions that it's already explored.
public void solveStack() throws IOException {
//save the maze
//MazeGenerator savedMaze = new MazeGenerator();
//savedMaze.clone(m);
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "+");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty()) {
System.out.println("You got it!");
}
else System.out.println("You're stuck in the maze!");
//savedMaze.print();
print();
restore(savedMaze);
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
Without the benefit of a maze.txt, I created one based on your description. Here's what I found...
Short answer:
Your program hits an infinite loop searching for the exit, so it never reaches the code to print it out.
Long answer:
I see 3 problems on 2 lines of code:
1) A simple typo:
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
getHeight() and getWidth() should be swapped:
if (row >= 0 && col >= 0 && row < getHeight() && col < getWidth() ) {
2) In one spot, you're using 1-based indices, when Java uses 0-based indices:
In this line here:
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
Array indices in java start at 0. Your row and col variables also start at 0. But you're adding one to them thereby converting them into 1-based indices. So, you'd want:
return (maze[row][col] != "1" && maze[row][col] != "+");
3) You're using != like !equals(), but in Java, == is not the same as .equals()
In the above line of code, you're comparing two Strings with the != operator. But that doesn't work like the String.equals() method, so your Clear() method always returns true.
This is the crux of your stated problem. The search routine, finding every cell clear, works its way into a corner, and then searches the same two adjacent cells forever.
So, what you really want is:
return (!maze[row][col].equals("1") && !maze[row][col].equals("+"));

2-D Maze Solver using Stack: ArrayIndexOutOfBoundsException [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but whenever i try to run it, i get an ArrayIndexOutOfBoundsException. I think the main problem is that there are no defined walls around the border. Maybe surround the maze with a border of 1's?
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++) { //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing values of maze
}
System.out.println(); // new line
}
}
public int size() {
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col] != "1" && maze[row][col] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col<size() && row>= 0 && col<size()) {
return true;
}
else if (row < 0 && col<size() && row >= 0 && col<size()) {
return false;
}
else return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void solveStack() throws IOException {
//save the maze
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "S");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty())
System.out.println("You got it!");
else System.out.println("You're stuck in the maze!");
print();
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
The error is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MazeGenerator.Clear(MazeGenerator.java:137)
at MazeGenerator.Clear(MazeGenerator.java:141)
at MazeGenerator.solveStack(MazeGenerator.java:217)
at MazeGenerator.main(MazeGenerator.java:40)
i think you're doing a mistake in inMaze(int row, int col) method. I'll try to correct it for you
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
therefore you have to change the size() method into getWidth() and getHeight()
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}

Sorting an Array with HeapSort

We have to sort an Array with random numbers. For this, we need to use this part of code ( HeapSort )
import java.util.ArrayList;
public class HeapSort<E extends Comparable<E>> {
public ArrayList<E> h;
public int SIZE;
public int n;
public HeapSort(int s){
SIZE=s;
n=1;
h=new ArrayList<>(SIZE);
for(int i=0;i<SIZE;i++)
h.add(null);
}
public void Insert(E e){
h.set(n,e);
n++;
// swapping up
if(n!=2){ // more than 1 element
int s=n-1; // last added element
int p=s/2; // its parent
while(s!=1 && LT(s,p)){
swap(p,s);
s=p;
p=p/2;
}
}
}
public boolean Empty(){
return n==1;
}
public E Lesser(){
return h.get(1);
}
public void Delete(){
n--;
h.set(1,h.get(n)); // last element to the root
h.set(n,null);
// swapping down
int ip=1;
int ils=2;
int irs=3;
while(ConditionSwapDown(ip,ils,irs)){
if(Exists(ils) && Exists(irs)){
// two sons
if(LT(ils,ip) || LT(irs,ip)){
// at least one child is lesser than the parent -> swap
if(LT(ils,irs)){
swap(ip,ils); // swapping down left
ip=ils;
ils=ip*2;
irs=ils+1;
}
else{
swap(ip,irs); // swapping down right
ip=irs;
ils=ip*2;
irs=ils+1;
}
}
}
else
// only left son
if(Exists(ils) && !Exists(irs)){
if(LT(ils,ip)){ // left son is lesser than the parent
swap(ip,ils);
ip=ils;
ils=ip*2;
irs=ils+1;
}
}
// else no children and end of swapping down
}
}
public boolean ConditionSwapDown(int p,int l,int r){
// (has 2 children and (parent>left or parent>right)) or
// (has 1 children and parent>left)
return (((Exists(l) && Exists(r)) && (LT(l,p) || LT(r,p)))) ||
(Exists(l) && !Exists(r) && LT(l,p));
}
public boolean Exists(int p){
if(p>=SIZE)
return false;
return h.get(p)!=null;
}
public void swap(int a,int b){
E c=h.get(a);
h.set(a,h.get(b));
h.set(b,c);
}
public boolean LT(int a,int b){ // h[a]<h[b]
return h.get(a).compareTo(h.get(b))<0;
}
#Override
public String toString(){
String r="";
for(int i=1;i<n;i++)
r+=h.get(i)+" ";
return r;
}
public String Print(){
return PrintR(1,"");
}
public String PrintR(int i,String p){
String r=p+h.get(i)+"\n";
if(h.get(i*2)!=null || h.get(i*2+1)!=null){
if(h.get(i*2)!=null)
r+=PrintR(i*2,p+" ");
else
r+=p+" -\n";
if(h.get(i*2+1)!=null)
r+=PrintR(i*2+1,p+" ");
else
r+=p+" -\n";
}
return r;
}
How do we "connect" the two codes? or use our array with HeapSort? For the Array we have done this:
public class P3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Quina llargada tindrĂ  la taula? ");
int n = reader.nextInt(); //n=llargada taula
int[] taula = new int[n];
int fi = 100*n;
Random rand = new Random();
//int al = rand.nextInt(fi) + 0;
for (int i = 0; i < taula.length; i++)
taula[i] = rand.nextInt(fi);
System.out.println(Arrays.toString(taula)); }}
Everything is in the HeapSort class, waiting for you to use it:
int[] taula = {4, 2, 8, 1, 2, 3};
System.out.println(Arrays.toString(taula));
// 'heapSort' variable will store ordered list
HeapSort<Integer> heapSort = new HeapSort<>(taula.length+1);
for (Integer i : taula)
heapSort.Insert(i);
System.out.println(heapSort);

using Java Loop for ArrayList to print each time

I have a method which I basically want to simulate first filling the queue and then after that removing the first person and adding a new person each time in my public void mySimulation() method:
import java.util.*;
public class People {
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private ArrayList<thePeople> people;
private int theMaxCapacity;
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public People(int initialCapacity) {
front = rear = count = 0;
people = new ArrayList<thePeople>(Collections.nCopies(5, (thePeople) null));
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enque(thePeople element) {
if (this.isFull()) {
System.out.println("Queue Full");
System.exit(1);
} else {
people.set(rear, element);
rear = rear + 1;
if (rear == people.size()) {
rear = 0;
}
count++;
}
}
//-----------------------------------------------------------------
// Removes the element at the front of the queue and returns a
// reference to it. Throws an EmptyCollectionException if the
// queue is empty.
//-----------------------------------------------------------------
public thePeople dequeue() {
if (isEmpty()) {
System.out.println("Empty Queue");
}
thePeople result = people.get(front);
people.set(front, null);
front = (front + 1) % people.size();
count--;
return result;
}
//-----------------------------------------------------------------
// Returns true if this queue is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty() {
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this queue.
//-----------------------------------------------------------------
public int size() {
return count;
}
public boolean isFull() {
return count == people.size();
}
public void mySimulation() {
Random rand1 = new Random();
thePeople theM = null;
if (this.isFull()) {
this.people.remove(0);
System.out.println("Enqueueing...");
this.enque(people.get(rand1.nextInt(people.size())));
thePeople r1 = people.get(rear - 1);
System.out.println(people.toString());
System.out.println(r1);
for (int e = 0; e < people.size(); e++) {
if (people.get(e) instanceof thePeople) {
System.out.println("G");
} else {
System.out.println("D");
}
}
}
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
#Override
public String toString() {
String result = "";
int scan = 0;
while (scan < count) {
if (people.get(scan) != null) {
result += people.get(scan).toString() + "\n";
}
scan++;
}
return result;
}
public static void main(String[] args) {
People Q1 = new People(25);
thePeople call1 = new thePeople("John King", "001 456 789");
thePeople call2 = new thePeople("Michael Fish", "789 654 321");
Q1.enque(call1);
Q1.enque(call2);
System.out.println(Q1.toString());
ArrayList<thePeople> callerDetails = new ArrayList<>(Arrays.asList(call1, call2));
Random rand = new Random();
for (int z = 0; z <= 4; z++) {
Q1.enque(callerDetails.get(rand.nextInt(callerDetails.size())));
}
System.out.println(Q1.toString());
}
}
any suggestions on how I could repeat this process such that I will first check that the queue is full,
if so remove the first item and add a new person to it using my arrayList each time i my my public void mySimulation() method: as I cant get my head round this at the moment?
Your code is filled with errors:
First make sure you remove the "the" you accidently placed before people in many lines of your code .
Then adjust some of your methods to the right parameters and return types.
As for you question:
it is simple
public void MySimulation(){
if(Queue.isFull()){
Queue.dequeue;}
Queue.enqueue;}

Categories

Resources