Java, constructor not working - java

So in a few words i made a class extending the RandomGenerator to randomly giving back PRIME, POWER OF 2(2,4,8,16,32,64,128 etc) , FIBONACCI AND SQUARE NUMBERS (1,4,9,16,25,36 etc). Then i made a simple program to call my class and giving back random numbers while the user defines the space (1,n). Both programs compile just fine. My problem is that when i run the program it always returns 0 for each value. I'm new to java. Can anyone help me?
import acm.util.*;
public class RandomGeneratorImproved2 extends RandomGenerator
{
private int i,j,a,c,d,e,temp,n,Pnumber,Fnumber,number2,numbersq;
private long b;
boolean flag,flag2,flag3,flag4,flag5;
private double temp1;
public RandomGeneratorImproved2 (int n)
{
this.n = n;
}
public void nextPrime(int n) // PRIME NUMBERS
{
Pnumber = rgen.nextInt(1, n);
i=2;
flag2 = false;
if ( Pnumber == 1 ) // Check for value 1 cause it cannot check it inside the loop
{
flag2=true;
}
while ( (i<n) && (flag2 == false) )
{
flag = true;
j=2;
do
{
a = i%j;
if ( (a == 0) && (i != j) )
{
flag = false;
}
if (i!=j-1)
{
j = j+1;
}
} while ( j<i );
if ((flag == true) && (Pnumber==i)) //
{
flag2 = true;
}
if ((i==99) && (flag2==false)) // restart if the number is not prime
{
i = 1;
Pnumber = rgen.nextInt(1, n);
}
i = i + 1;
}
}
public int getPrime() //POWER OF 2 NUMBERS
{
return Pnumber;
}
public void nextPowerof2(int n)
{
number2 = rgen.nextInt(1, n);
i=1;
b=2;
flag3 = false;
while ( i<n ) // n <= 31
{
if (number2 == b)
{
flag3 = true;
}
b = 2*b;
if ((i == n-1) && (flag3==false))
{
i=1;
number2 = rgen.nextInt(1,n);
b=2;
}
i=i+1;
}
}
public int getPowerof2()
{
return number2;
}
public void nextFibonacciNumber(int n) // FIBONACCI NUMBERS
{
Fnumber = rgen.nextInt(1, n);
c=0;
d=1;
flag4 = false;
i=1;
while ( i<n && flag4==false )
{
temp = d;
d = d + c;
c = temp;
i=i+1;
if (Fnumber == d)
{
flag4 = true;
}
if ((flag4 == false) && (i==n))
{
i=1;
c=0;
d=1;
Fnumber = rgen.nextInt(1, n);
}
}
}
public int getFibonacciNumber()
{
return Fnumber;
}
public void setSquareNumber(int n) // SQUARE NUMBERS
{
numbersq = rgen.nextInt(1, n);
flag5 = false;
i=1;
temp1 = Math.sqrt(n);
while ( i<temp1 && flag5 == false )
{
e = i*i;
i = i + 1;
if ( numbersq == e )
{
flag5 = true;
}
if ( i == 20 && flag5 == false )
{
i=1;
numbersq = rgen.nextInt(1, n);
}
}
}
public int getSquareNumber()
{
return numbersq;
}
public String toString()
{
return "Your Prime number is : " + Pnumber + "\nYour Power of 2 number is : " + number2 + "\nYour Fibonacci number is : " + Fnumber + "\nYour square number is : " + numbersq;
}
private RandomGenerator rgen = RandomGenerator.getInstance();
}
import acm.program.*;
public class caller2 extends Program
{
public void run()
{
int n = readInt("Please give me an integer to define the space that i'll look for numbers : ");
RandomGeneratorImproved2 r1 = new RandomGeneratorImproved2(n);
println(r1);
}
}

As stated you've only defined those method. You never call any of the methods that are setting those values so all are still in their initialized state. Try adding the following to the constructor after setting n;
nextPrime(n);
nextFibonaccitNumber(n);
nextPowerof2(n);

Related

Java assignment to use Dijkstras search method, breath-first and depth first

Hello StackOverflow community, need your help. I have a final for my java class and its asking for:
Generate a graph with 100,000 nodes, where each node randomly has between 1 and 5 connections to other nodes. Each node should contain within it a random value between 1 and 300,000. (So generally about 1 in 3 searches will yield a query match). Allow the user to enter a number to search for, and implement each of the following three types of searching algorithms. Breadth-First. (30 points) Depth-First. (30 points) Dijkstra's Algorithm. (40 points)
Do not allow back-tracking in your searches. (Mark nodes that you already searched as complete, and do not re-visit them in the same search). Each search should return the following: The Success/Failure of your search. The length of the shortest path to the found node. The total number of nodes examined during the search. Optionally you may return the exhaustive display of the shortest path, for testing and verification.
For some reason, my IDE shows that BFS and Dijkstras has "duplicated code fragment 17 lines long" can someone look at tell me how to fix it or maybe a better way to implement it? Also, if i try to do nodesNum > 30k in "Driver Class" i get a memory leak.
Here is the code:
Class Graph:
import java.util.*;
import javax.swing.JOptionPane;
class Graph
{
private Listing[] vertex;
private int[][] edge;
private int max;
private int numberOfVertices;
private int nodeCheck = 0;
private int selectNum = 0;
Graph(int g)
{
vertex = new Listing[g];
edge = new int[g][g];
max = g;
numberOfVertices = 0;
}
private void depthFirstSearch(int firstVertex)
{
int v;
Stack<Integer> nodeStack = new Stack<>();
for(int i = 0; i<numberOfVertices; i++)
{
if (vertex[i] != null) {
vertex[i].setPushed(false);
}
}
nodeStack.push(firstVertex);
vertex[firstVertex].setPushed(true);
while (!nodeStack.empty())
{
v = nodeStack.pop();
vertex[v].visit();
nodeCheck++;
for (int column = 0; column < numberOfVertices; column++)
{
if(edge[v][column] == 1 && vertex[column].getPushed())
{
nodeStack.push(column);
vertex[column].setPushed(true);
}
}
}
}
private void breathFirstSearch(int firstVertex)
{
int V;
Queue<Integer> nodeQueue = new LinkedList<>();
for(int i = 0; i < numberOfVertices; i++)
{
if(vertex[i] != null)
vertex[i].setPushed(false);
}
nodeQueue.add(firstVertex);
vertex[firstVertex].setPushed(true);
while(!nodeQueue.isEmpty())
{
V = nodeQueue.remove();
vertex[V].visit();
nodeCheck++;
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[V][column] == 1 && vertex[column].getPushed())
{
nodeQueue.add(column);
vertex[column].setPushed(true);
}
}
}
}
private void Dijkstra(int firstVertex)
{
int v;
LinkedList<Integer> nodeQueue = new LinkedList<>();
int i = 0;
while (i < numberOfVertices)
{
if(vertex[i] != null)
vertex[i].setPushed(false);
i++;
}
nodeQueue.add(firstVertex);
vertex[firstVertex].setPushed(true);
while(!nodeQueue.isEmpty())
{
v = nodeQueue.remove();
vertex[v].visit();
nodeCheck++;
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[v][column] == 1 && vertex[column].getPushed())
{
nodeQueue.add(column);
vertex[column].setPushed(true);
}
}
}
}
private void insertVertex(int vertexNumber, Listing newListing)
{
if(vertexNumber >= max)
{
return;
}
vertex[vertexNumber] = newListing.deepCopy();
numberOfVertices++;
}
private void insertEdge(int fromVertex, int toVertex)
{
if(vertex[fromVertex] == null || vertex[toVertex] == null)
return;
edge[fromVertex][toVertex] = 1;
}
void showVertex(int vertexNumber)
{
System.out.print(vertex[vertexNumber]);
}
void showEdges(int vertexNumber)
{
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[vertexNumber][column] == 1)
{
System.out.println(vertexNumber + "," + column);
}
}
System.out.println();
}
void InitializeNodes(Graph G, int nodesNum)
{
Random random = new Random();
for (int i = 0; i < nodesNum; i++ )
{
Listing v = new Listing(random.nextInt(300000) + 1);
G.insertVertex(i, v);
}
int vertexListNumber = G.vertex.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nodesNum; i++ )
{
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < vertexListNumber; i++ )
{
int randnum = random.nextInt(5);
for (int j = 0; j < randnum; j++ )
{
int rand = random.nextInt(5);
G.insertEdge(i, list.get(rand));
}
}
}
int Search()
{
String search = JOptionPane.showInputDialog("Enter Node to search:");
try
{
if(search != null)
{
selectNum = Integer.parseInt(search);
}
}
catch (NumberFormatException e)
{
selectNum = 0;
}
return selectNum;
}
private int SelectPane()
{
String paneSelect = JOptionPane.showInputDialog("Choose a search method:" +
"\n\t1: Use Depth-First Search" +
"\n\t2: Use Breadth-First Search" +
"\n\t3: Use Dijkstra's Search" +
"\n\t4: Close Program");
int selectNum = 0;
try{
if(paneSelect != null)
{
selectNum = Integer.parseInt(paneSelect);
}
}
catch (NumberFormatException ignored)
{
}
return selectNum;
}
void algorithmChoice(Graph graph, int vertexStart)
{
int paneNum = 0;
while (paneNum != 4)
{
paneNum = SelectPane();
switch (paneNum)
{
case 1:
graph.depthFirstSearch(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 2:
graph.breathFirstSearch(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 3:
graph.Dijkstra(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 4:
break;
default:
JOptionPane.showMessageDialog(null, "Enter 4 to quit.");
break;
}
}
}
}
Class Listing:
public class Listing
{
private int value;
private boolean pushed;
Listing(int v)
{
value = v;
}
public String toString()
{
return ("Vertex: " + value + "\n" );
}
Listing deepCopy()
{
return new Listing(value);
}
boolean getPushed()
{
return !pushed;
}
void setPushed(boolean value)
{
pushed = value;
}
void visit()
{
System.out.println(this);
}
}
Class Driver:
public class Driver
{
public static void main(String[] args)
{
int nodesNum = 30000; //Can go up to 30k nodes, otherwise causes memory leak.
Graph graph = new Graph(nodesNum);
graph.InitializeNodes(graph, nodesNum);
for(int i = 0; i<5; i++)
{
System.out.print("Node " + i + "\'s ");
graph.showVertex(i);
System.out.print("Its routes are:\n");
graph.showEdges(i);
}
int select = graph.Search();
graph.algorithmChoice(graph, select);
}
}
Thanks alot for your help!
The error you get is due to exceeding max heap size when creating a edge = new int[g][g]; where g can be as high as 100,000 in your case.
I would suggest avoiding the use of such huge matrix.
Instead introduce an Edge object :
class Edge{
private final int fromVertex, toVertex;
Edge(int fromVertex, int toVertex){
this.fromVertex = fromVertex;
this.toVertex = toVertex;
}
#Override
public boolean equals(Object obj) {
if( ! (obj instanceof Edge)) return false;
Edge other = (Edge)obj;
return connects(other.fromVertex, other.toVertex);
}
boolean connects(int fromVertex, int toVertex){
return fromVertex == this.fromVertex && toVertex == this.toVertex ||
fromVertex == this.toVertex && toVertex == this.fromVertex;
}
}
and use it in Graph.
Instead of private int[][] edge; use a collection of Edges:
private final Set<Edge> edges = new HashSet<>();
Change insertEdge to:
private void insertEdge(int fromVertex, int toVertex)
{
if(vertex[fromVertex] == null || vertex[toVertex] == null)
return;
edges.add(new Edge(fromVertex, toVertex));
}
and add a method to check if there is an edge between two vertices:
private boolean isEdgeBetween(int fromVertex, int toVertex)
{
for(Edge edge : edges){
if(edge.connects(fromVertex, toVertex)) return true;
}
return false;
}
Usage : if( isEdgeBetween(v,column) && vertex[column].getPushed())
instead of: if(edge[v][column] == 1 && vertex[column].getPushed())

2 same-class objects being instantiated by another same-class object error

I am currently implementing Eight Puzzle problem using A* Algorithm (Hamming) method and have provided code :
public class Board
{
int board[][];
public Board()
{
board = new int[3][3];
}
public void initialise(int n1, int n2, int n3, int n4, int n5, int n6, int n7, int n8, int n9)
{
//first row
board[0][0] = n1;
board[0][1] = n2;
board[0][2] = n3;
//second row
board[1][0] = n4;
board[1][1] = n5;
board[1][2] = n6;
//third row
board[2][0] = n7;
board[2][1] = n8;
board[2][2] = n9;
}
public int states_out_of_order()
{
int count = 0;
for(int i = 0; i < 3; i++)
{
//Checking if first row is
//1 2 3
if(i==0)
{
if(board[i][0]!=1)
{
count++;
}
if(board[i][1]!=2)
{
count++;
}
if(board[i][2]!=3)
{
count++;
}
}
//Checking if second row is
//4 5 6
if(i==1)
{
if(board[i][0]!=4)
{
count++;
}
if(board[i][1]!=5)
{
count++;
}
if(board[i][2]!=6)
{
count++;
}
}
//Checking if second row is
//7 8 0
if(i==2)
{
if(board[i][0]!=7)
{
count++;
}
if(board[i][1]!=8)
{
count++;
}
if(board[i][2]!=9)
{
count++;
}
}
}
return count;
}
public boolean GoalStateCheck()
{
//Checking first row
if(board[0][0]!=1)
{
return false;
}
if(board[0][1]!=2)
{
return false;
}
if(board[0][2]!=3)
{
return false;
}
//Checking second row
if(board[1][0]!=4)
{
return false;
}
if(board[1][1]!=5)
{
return false;
}
if(board[1][2]!=6)
{
return false;
}
//Checking third row
if(board[2][0]!=7)
{
return false;
}
if(board[2][1]!=8)
{
return false;
}
if(board[2][2]!=0)
{
return false;
}
return true;
}
public void printBoard()
{
System.out.print(board[0][0] + " " + board[0][1] + " " + board[0][2]);
System.out.println();
System.out.print(board[1][0] + " " + board[1][1] + " " + board[1][2]);
System.out.println();
System.out.print(board[2][0] + " " + board[2][1] + " " + board[2][2]);
System.out.println();
}
}
And now the solver class
import java.util.ArrayList;
public class Solver
{
ArrayList<Board> list;
int steps;
public Solver()
{
list = new ArrayList<Board>();
steps = 0;
}
public Board SwapStates(Board b, int a[][], int r1, int c1, int r2, int c2)
{
int temp = a[r1][c1];
a[r1][c1] = a[r2][c2];
a[r2][c2] = temp;
return b;
}
//Find the board in ArrayList according the number of states out of order
public Board findBoard(int num)
{
for(int i = 0; i < list.size(); i++)
{
if(num == list.get(i).states_out_of_order())
{
return list.get(i);
}
}
return null;
}
//Choose the puzzle state with minimum states that are out of order
public int min()
{
int n = 10;
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).states_out_of_order() < n)
{
n = list.get(i).states_out_of_order();
}
}
return n;
}
//Find the board in ArrayList and remove it
public void matchRemove(Board b)
{
for(int i = 0; i < list.size(); i++)
{
if(b == list.get(i))
{
list.remove(list.get(i));
break;
}
}
}
public void Hamming(Board b)
{
boolean solved = b.GoalStateCheck();
while(!solved)
{
if(b.board[0][0] == 0)
{
//Pointer to original board
final Board ptr = b;
Board b1 = ptr;
Board b2 = ptr;
//Check move #1 from original state
b1 = SwapStates(b1, b1.board,0,0,0,1);
//Check move #2 from original state
//Problem is that it is not swapping ptr but rather its swapping b1. why?
b2 = SwapStates(b2, b2.board,0,0,1,0);
//Add the moves to the Arraylist
list.add(b1);
list.add(b2);
//Find the board with minimum number of states out of order and remove it frm list
int n = min();
Board temp = findBoard(n);
matchRemove(temp);
//Assign removed board as optimum move
b = temp;
steps++;
b.printBoard();
}
else if(b.board[0][1] == 0)
{
}
else if(b.board[0][2] == 0)
{
}
else if(b.board[1][0] == 0)
{
}
else if(b.board[1][1] == 0)
{
}
else if(b.board[1][2] == 0)
{
}
else if(b.board[2][0] == 0)
{
}
else if(b.board[2][1] == 0)
{
}
else if(b.board[2][2] == 0)
{
}
else
{
System.out.println("Board is not in its proper form");
break;
}
}
/*System.out.println("Goal State has been achieved!!");
System.out.println("It took " + steps + " moves");
b.printBoard();*/
}
}
In the Hamming function of my Solver class at the first if statement i have this line
final Board ptr = b;
Board b1 = ptr;
Board b2 = ptr;
However when at these two lines:
//Check move #1 from original state
b1 = SwapStates(b1, b1.board,0,0,0,1);
//Check move #2 from original state
//Problem is that it is not swapping ptr but rather its swapping b1. why?
b2 = SwapStates(b2, b2.board,0,0,1,0);
b2 is using the swapped state of b1 instead of the original ptr which i want to use. why?
When you've written
final Board ptr = b;
Board b1 = ptr;
Board b2 = ptr;
You did not create an immutable copy of b called ptr and two mutable copies of ptr called b1 and b2.
You simply created 3 references to the same object. Any modification on the object using any of the 4 references will end up affecting the object in the same way and thus, change the visible state for all 4 references.
What you should do is add a public Board copy() method in your board class which would return another instance of Board (using a new Board() and copying values) and change your code by :
final Board ptr = b.copy(); // but is there any sense to use ptr rather than b ?
Board b1 = ptr.copy();
Board b2 = ptr.copy();

I'm trying to perform integer division on numbers greater than size of any data type available

As far big numbers are concerned, i know there is a class available in java BigInteger, but i have a constraint that i can't use this and i have to perform division without using library.
This is what i have tried so far, but got memory leakage issues and not getting any answer
private Integer getDivisionResult(ArrayList<Integer> first, ArrayList<Integer> second) {
int firstLength = first.size();
int secondLength = second.size();
int counter = 0;
if (firstLength < secondLength) {
return counter;
}
do {
int carry = 0, cursor1 = firstLength - 1, cursor2 = secondLength - 1;
for (int i = firstLength - 1; i >= 0; i--, cursor1--, secondLength--) {
int value = 0, from = 0;
from = first.get(cursor1) - carry;
if (from < (cursor2 < 0 ? 0 : second.get(cursor2))) {
if (cursor1 > 0) {
from = 10 + from;
}
carry = 1;
} else {
carry = 0;
}
value = from - (cursor2 < 0 ? 0 : second.get(cursor2));
first.set(i, value);
}
counter++;
}while (isLesserThan(second,first));
return counter;
}
private boolean isLesserThan(ArrayList<Integer> list, ArrayList<Integer> firstList) {
boolean result = true;
if (list.size() < firstList.size()) {
return true;
}
for (int i = 0; i < list.size(); i++) {
if (firstList.get(i) > list.get(i)) {
result = true;
break;
} else if (firstList.get(i) == list.get(i)) {
continue;
} else {
result = false;
break;
}
}
return result;
}
I'm calling getDivisionResult inside this method, after passing certain error cases:
/**
* #param numOne
* #param numTwo
* #return sign : true (negative) , false (positive)
*/
public Result getResult(String numOne, String numTwo) {
Result result = new Result();
int res = 0;
boolean sign = false;
ArrayList<Integer> firstNum;
ArrayList<Integer> secondNum;
if (isNegative(numOne)) {
firstNum = getArray(numOne.substring(1));
if (isNegative(numTwo)) {
sign = false;
secondNum = getArray(numTwo.substring(1));
} else {
secondNum = getArray(numTwo);
sign = true;
}
} else {
firstNum = getArray(numOne);
if (isNegative(numTwo)) {
sign = true;
secondNum = getArray(numTwo.substring(1));
} else {
secondNum = getArray(numTwo);
}
}
if (isNull(secondNum)) {
result.setSign("Division by 0 is not permissable");
result.setValue(res);
return result;
} else {
if (isNull(firstNum)) {
result.setSign("");
result.setValue(res);
return result;
}
firstNum = getNumberWithoutZeroes(firstNum);
secondNum = getNumberWithoutZeroes(secondNum);
res = getDivisionResult(firstNum, secondNum);
if (sign) {
result.setSign("-");
} else {
result.setSign("");
}
result.setValue(res);
}
return result;
}
private ArrayList<Integer> getNumberWithoutZeroes(ArrayList<Integer> num) {
ArrayList<Integer> list = new ArrayList<>();
for (Integer x : num) {
if (x == 0) {
continue;
} else {
list.add(x);
}
}
return list;
}
private boolean isNegative(String num) {
boolean result = false;
if (num.startsWith("-")) {
result = true;
}
return result;
}
private boolean isNull(ArrayList<Integer> num) {
boolean result = true;
for (Integer x : num) {
if (x > 0) {
result = false;
}
}
return result;
}
private ArrayList<Integer> getArray(String num) {
ArrayList<Integer> list = new ArrayList<>();
char[] arr = num.toCharArray();
for (int i = 0; i < num.length(); i++) {
list.add(Integer.valueOf(arr[i]));
}
return list;
}
if someone can help me to give a better solution to my problem, I would be grateful
I've made the solution to my own problem, but the problem now is its processing speed.

NullPointerException even when variables are not null

I'm currently designing a program to simulate an airport. I ran into a problem and I've already tried my best to figure out the problem and posting to this site was my final resort.
It keeps giving me a "Exception in thread "main" java.lang.NullPointerException at AirportApp.main(AirportApp.java:119)" which is under the //Landings section with the code
System.out.println(plane1.getCapacity());
The reason I did the print is to make sure plane1.getCapacity isn't a null. This is because when I tried the code below it
if(plane1.getCapacity() < 300);
it gave me the NullPointerException error. I did the print and it didn't return a null.
What I'm trying to do here is whenever a plane lands, it will be assigned to an empty gate. If the plane has a capacity of 300 or more, it will be assigned to the 4th or 5th gate only. The other planes can be assigned to any gate.
What I noticed was that the error happens only when the capacity is over 300.
I've already looked at my code over and over again making sure all variables were initialized and I still could not find anything wrong. Any help or hints will be greatly appreciated. Apologies for the messy code.
Main class.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class AirportApp {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();
String [] flightNames = {"SQ", "MI", "TZ", "TR", "EK", "MO", "FC"};
int [] flightNum = {8421, 5361, 6342, 6135, 8424, 7424, 5435};
Queue landingRunway = new Queue(10);
Queue takeoffRunway = new Queue(10);
Queue planesQueue = new Queue(100);
Queue gatesQueue = new Queue(100);
ArrayList<Gate> allGates = new ArrayList();
for(int i = 1 ; i < 6 ; i++)
{
allGates.add(new Gate(i, 0, 0, true));
}
int minutes = 0;
int planesMissedTime = 0;
Boolean highWinds = null;
int tookOffPlanes = 0;
int smallCapPlanes = 0;
int largeCapPlanes = 0;
int landedPlanes = 0;
System.out.println("Please key in the number of minutes you want "
+ "the program to run: ");
int desiredMinutes = sc.nextInt();
while(minutes < desiredMinutes)
{
//Randomise wind warnings
int windRandom = rn.nextInt(2) + 1;
if(windRandom == 1)
{
highWinds = true;
}
if(windRandom == 2)
{
highWinds = false;
}
//Empty the gates
for(Gate c : allGates)
{
if(c.getAvailability() == false)
{
c.addMinInQueue(1);
if(c.getMinInQueue() == 15)
{
c.isAvailable();
}
}
}
//Every 2 minutes
if(minutes % 2 == 0)
{
//Randomise flight names and number
int index = rn.nextInt(flightNames.length);
int index1 = rn.nextInt(flightNum.length);
String name = flightNames[index];
int num = flightNum[index1];
//Randomise plane assignment
int planeDirection = rn.nextInt(2) + 1;
int planeCap = rn.nextInt(401) + 100;
//Arrival Planes
if(planeDirection == 1)
{
planesQueue.enqueue(new Plane(num, name, planeCap, 5 , 0 ));
System.out.println("A plane has been generated.");
}
//Departure Planes
if(planeDirection == 2)
{
planesQueue.enqueue(new Plane(num, name, planeCap, 0 , 5 ));
System.out.println("A plane has been generated.");
}
//Take-Offs
if(!takeoffRunway.isEmpty())
{
System.out.println("A plane has departed.");
Plane departPlane = (Plane) takeoffRunway.dequeue();
if (departPlane.getCapacity() < 300)
{
smallCapPlanes++;
}
tookOffPlanes++;
}
}
//Landings
if(minutes % 3 == 0 && !landingRunway.isEmpty())
{
System.out.println("A plane has landed.");
gatesQueue.enqueue(landingRunway.dequeue());
landedPlanes++;
loop1:
for(Gate e : allGates)
{
if(e.getAvailability() == true)
{
Plane plane1 = (Plane) gatesQueue.dequeue();
System.out.println(plane1.getCapacity());
if(plane1.getCapacity() < 300)
{
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
if(plane1.getCapacity() > 300)
{
largeCapPlanes++;
if(e.getGateId() == 4 || e.getGateId() == 5)
{
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
}
}
}
}
//Plane assigned to takeoff or landing queue
if(minutes % 5 == 0)
{
Plane item = (Plane) planesQueue.peek();
if(item.getArrivalTime() == 5 && landingRunway.isEmpty()
&& highWinds == false)
{
landingRunway.enqueue(planesQueue.dequeue());
System.out.println("A plane has been assigned to "
+ "the landing queue.");
}
else if(item.getDepartureTime() == 5 &&
takeoffRunway.isEmpty() && highWinds == false)
{
takeoffRunway.enqueue(planesQueue.dequeue());
System.out.println("A plane has been assigned to "
+ "the takeoff queue.");
}
else
{
planesMissedTime++;
}
}
minutes++;
}
Class 1
public class Plane
{
private int flightNo;
private String flightName;
private int capacity;
private int timeOfArrival;
private int timeOfDeparture;
private int delayTime;
public Plane(int flightNo, String flightName, int capacity,
int timeOfArrival, int timeOfDeparture)
{
this.flightNo = flightNo;
this.flightName = flightName;
this.capacity = capacity;
this.timeOfArrival = timeOfArrival;
this.timeOfDeparture = timeOfDeparture;
}
public void setFlightNum(int flightNo)
{
this.flightNo = flightNo;
}
public int getFlightNum()
{
return this.flightNo;
}
public void setFlightName(String flightName)
{
this.flightName = flightName;
}
public String getflightName()
{
return this.flightName;
}
public void addCapacity(int capacity)
{
this.capacity = capacity;
}
public int getCapacity()
{
return this.capacity;
}
public void setArrivalTime(int newArrivalTime)
{
this.timeOfArrival = newArrivalTime;
}
public int getArrivalTime()
{
return this.timeOfArrival;
}
public void setDepartureTime(int newDepartureTime)
{
this.timeOfDeparture = newDepartureTime;
}
public int getDepartureTime()
{
return this.timeOfDeparture;
}
}
Class 2
public class Gate
{
private int gateID;
private int numOfPlanes;
private int minInQueue;
private boolean availability;
public Gate(int id, int numPlanes, int minQueue, boolean available)
{
this.gateID = id;
this.numOfPlanes = numPlanes;
this.minInQueue = minQueue;
this.availability = available;
}
public int getGateId()
{
return this.gateID;
}
public void setGateId(int newID)
{
this.gateID = newID;
}
public int getNumOfPlanes()
{
return this.numOfPlanes;
}
public void addNumOfPlanes(int addNum)
{
this.numOfPlanes += addNum;
}
public int getMinInQueue()
{
return this.minInQueue;
}
public void setMinInQueue(int setMin)
{
this.minInQueue = 0;
}
public void addMinInQueue(int addMin)
{
this.minInQueue += addMin;
}
public boolean getAvailability()
{
return this.availability;
}
public void setAvailability(Boolean setAvailability)
{
this.availability = setAvailability;
}
public void isAvailable()
{
this.availability = true;
this.minInQueue = 0;
}
}
Queue class
class Queue
{
private int count;
private int front = 0;
private int rear = 0;
private Object [] items;
public Queue(int maxSize)
{
count = 0;
front = -1;
rear = -1;
items = new Object [maxSize];
}
public boolean enqueue (Object x)
{
if (count == items.length)
{
return false;
}
else
{
rear = (rear + 1) % items.length;
items[rear] = x;
if (count == 0)
{
front = 0;
}
count++;
return true;
}
}
public Object dequeue()
{
if (count == 0)
{
return null;
}
else
{
Object result = items[front];
front = (front + 1) % items.length;
count--;
if (count == 0)
{
front = -1;
rear = -1;
}
return result;
}
}
public int size()
{
return count;
}
public boolean isEmpty()
{
if (count == 0)
{
return true;
}
else
{
return false;
}
}
public Object peek()
{
if (count == 0)
{
return null;
}
else
{
return items[front];
}
}
}
The problem lies in the second if statement
if (plane1.getCapacity() > 300) {
largeCapPlanes++;
if (e.getGateId() == 4 || e.getGateId() == 5) {
e.addNumOfPlanes(1);
e.setAvailability(false);
break loop1;
}
}
You only break your loop if the gate is 4, or 5. So, if it is not gate 4 or 5, then you code will loop back to the next gate, grab another plane from the queue (which is empty and your plane1 is now null) and then try to get the capacity. And there you get your null pointer.
Note: Be careful nesting loops and if statements. This is where bugs enjoy living.
Happy Coding!
I ran the code and didn't get an error until I tried a large number for the time (1000). I'm assuming the error is with the Plane plane1 = (Plane) gatesQueue.dequeue(); section. I would throw some debug statements in there to see if for large n that the Queue is generated properly. if dequeue() returns null then plane1 will also be null
EDIT:
So I debugged it and confirmed that the issue is with your plane object in that loop. You enqueue your gates: gatesQueue.enqueue(landingRunway.dequeue()); then you run a loop: for(Gate e : allGates) and then you dequeue: Plane plane1 = (Plane) gatesQueue.dequeue();
If you dequeue more than what you enqueue you will return null. So you'll either have to change how you do your queue or put a check in that for-loop to check the size of your queue.
The reason you are seeing a number when you do your System.out.println() is because it is displaying that, returning to the top of the loop, and then trying to get the plane object again before you run the print again.

Polynomials in Java

My add method works, however when I create a new SparsePolynomial object (at the bottom of the add method), the value of the newSparePolynomial changes when I debug it and I can't figure out where the extra information is coming from. Can someone help me?
Here is a copy of my code:
import java.util.ArrayList;
public class SparsePolynomial {
private ArrayList<Polynomial> polynomialarraylist = new ArrayList<Polynomial>();
/**
* Constructor to get values of an arraylist of integers
* #param arraylist that contains the integer values used for the polynomials
*/
public SparsePolynomial(ArrayList<Integer> arrayList)
{
//MODIFIDED: polynomialarraylist
//EFFECT: constructs the arraylist of polynomials based off the arraylist of integers
insertIntoPolynomialArray(arrayList);
}
/**
* Converts the elements of the integer array into polynomials
* #param arrayList that contains the polynomials contents
*/
private void insertIntoPolynomialArray(ArrayList<Integer> arrayList)
{
//MODIFIED: polynomialarray
//EFFECT: inputs the values of the arrayList into the polynomial array based on the position of the digits
for(int i = 0; i < arrayList.size(); i++)
{
Polynomial polynomial = new Polynomial(arrayList.get(i), arrayList.get(i+1));
polynomialarraylist.add(polynomial);
System.out.println("coef" + arrayList.get(i));
System.out.println("degree" + arrayList.get(i+1));
i++;
}
}
/**
*
*/
#Override
public String toString()
{
String result = "";
sort();
if (getDegree(0) == 0)
return "" + getCoefficient(0);
if (getDegree(0) == 1)
return getCoefficient(0) + "x + " + getCoefficient(0);
result = getCoefficient(0) + "x^" + getDegree(0);
for (int j = 1; j < polynomialarraylist.size(); j++)
{
if(j > polynomialarraylist.size())
{
break;
}
if
(getCoefficient(j) == 0) continue;
else if
(getCoefficient(j) > 0) result = result+ " + " + ( getCoefficient(j));
else if
(getCoefficient(j) < 0) result = result+ " - " + (-getCoefficient(j));
if(getDegree(j) == 1) result = result + "x";
else if (getDegree(j) > 1) result = result + "x^" + getDegree(j);
}
return result;
}
/**
* Sorts array
* #param array to sort
*/
private void sort()
{
ArrayList<Polynomial> temp = polynomialarraylist;
ArrayList<Polynomial> temp2 = new ArrayList<Polynomial>();
int polydegreemain = polynomialarraylist.get(0).degree();
temp2.add(polynomialarraylist.get(0));
for(int i = 1; i < polynomialarraylist.size(); i++)
{
if(i > polynomialarraylist.size())
{
break;
}
int polydegreesecondary = polynomialarraylist.get(i).degree();
if(polydegreemain < polydegreesecondary)
{
temp.set(i-1, polynomialarraylist.get(i));
temp.set(i, temp2.get(0));
}
}
polynomialarraylist = temp;
}
/**
* Makes object hashable
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((polynomialarraylist == null) ? 0 : polynomialarraylist
.hashCode());
return result;
}
/**
* Checks for equality of two objects
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SparsePolynomial other = (SparsePolynomial) obj;
if (polynomialarraylist == null) {
if (other.polynomialarraylist != null)
return false;
} else if (!polynomialarraylist.equals(other.polynomialarraylist))
return false;
return true;
}
public boolean equals(SparsePolynomial Sparse)
{
if(this == Sparse)
{
return true;
}
else
{
return false;
}
}
public SparsePolynomial add(SparsePolynomial other)
{
ArrayList<Polynomial> thisPolynomial = createPolynomial();
SparsePolynomial newSparsePolynomial;
ArrayList<Polynomial> otherPolynomial = other.createPolynomial();
Polynomial oldsum = new Polynomial();
Polynomial newsum = new Polynomial();
for(int i = 0; i < thisPolynomial.size();i++)
{
if(thisPolynomial.size() == 1)
{
newsum = thisPolynomial.get(i);
oldsum = newsum;
break;
}
if(i == 0)
{
newsum = thisPolynomial.get(i).add(thisPolynomial.get(i+1));
oldsum = newsum;
i++;
}
else
{
newsum = oldsum.add(thisPolynomial.get(i));
oldsum = newsum;
}
}
for(int i = 0; i < otherPolynomial.size(); i++)
{
newsum = oldsum.add(otherPolynomial.get(i));
oldsum = newsum;
}
ArrayList<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < oldsum.degree()+1; i++)
{
ints.add(oldsum.coefficient(i));
ints.add(i);
}
newSparsePolynomial = new SparsePolynomial(ints);
return newSparsePolynomial;
}
public SparsePolynomial subtract(SparsePolynomial other)
{
ArrayList<Polynomial> thisPolynomial = createPolynomial();
ArrayList<Polynomial> otherPolynomial = other.createPolynomial();
Polynomial olddifference = new Polynomial();
Polynomial newdifference = new Polynomial();
for(int i = 0; i < thisPolynomial.size()+1;i++)
{
if(i == 0)
{
newdifference = thisPolynomial.get(i).subtract(thisPolynomial.get(i+1));
olddifference = newdifference;
i++;
}
else
{
newdifference = olddifference.subtract(thisPolynomial.get(i));
olddifference = newdifference;
}
}
for(int i = 0; i < otherPolynomial.size(); i++)
{
newdifference = olddifference.add(otherPolynomial.get(i));
olddifference = newdifference;
}
ArrayList<Polynomial> polyarray = createArrayListOfPolynomialsFromPolynomials(olddifference);
ArrayList<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < polyarray.size(); i++)
{
ints.add(polyarray.get(i).coefficient(polyarray.get(i).degree()));
ints.add(polyarray.get(i).degree());
}
SparsePolynomial newSparsePolynomial = new SparsePolynomial(ints);
return newSparsePolynomial;
}
private int getDegree(int index)
{
int degree;
degree = polynomialarraylist.get(index).degree();
return degree;
}
private int getCoefficient(int index)
{
int coefficient;
coefficient = polynomialarraylist.get(index).coefficient(polynomialarraylist.get(index).degree());
return coefficient;
}
private ArrayList<Polynomial> createPolynomial()
{
Polynomial polynomial = null;
ArrayList<Polynomial> polynomialArray = new ArrayList<Polynomial>();
for(int i = 0; i < polynomialarraylist.size(); i++)
{
polynomial = new Polynomial(getCoefficient(i), getDegree(i));
polynomialArray.add(polynomial);
}
return polynomialArray;
}
Polynomial class
public class Polynomial {
// Overview: ...
private int[] terms;
private int degree;
// Constructors
public Polynomial() {
// Effects: Initializes this to be the zero polynomial
terms = new int[1];
degree = 0;
}
public Polynomial(int constant, int power) {
// Effects: if n < 0 throws IllegalArgumentException else
// initializes this to be the polynomial c*x^n
if(power < 0){
throw new IllegalArgumentException("Polynomial(int, int) constructor");
}
if(constant == 0) {
terms = new int[1];
degree = 0;
return;
}
terms = new int[power+1];
for(int i=0; i<power; i++) {
terms[i] = 0;
}
terms[power] = constant;
degree = power;
}
private Polynomial(int power) {
terms = new int[power+1];
degree = power;
}
// Methods
public int degree() {
// Effects: Returns the degree of this, i.e., the largest exponent
// with a non-zero coefficient. Returns 0 is this is the zero polynomial
return degree;
}
public int coefficient(int degree) {
// Effects: Returns the coefficient of the term of this whose exponent is degree
if(degree < 0 || degree > this.degree) {
return 0;
}
else {
return terms[degree];
}
}
public Polynomial subtract(Polynomial other) throws NullPointerException {
// Effects: if other is null throws a NullPointerException else
// returns the Polynomial this - other
return add(other.minus());
}
public Polynomial minus() {
// Effects: Returns the polynomial - this
Polynomial result = new Polynomial(degree);
for(int i=0; i<=degree; i++) {
result.terms[i] = -this.terms[i];
}
return result;
}
public Polynomial add(Polynomial other) throws NullPointerException {
// Effects: If other is null throws NullPointerException else
// returns the Polynomial this + other
Polynomial larger, smaller;
if (degree > other.degree){
larger = this;
smaller = other;
}
else {
larger = other;
smaller = this;
}
int newDegree = larger.degree;
if (degree == other.degree) {
for(int k = degree; k > 0 ; k--) {
if (this.terms[k] + other.terms[k] != 0) {
break;
}
else {
newDegree --;
}
}
}
Polynomial newPoly = new Polynomial(newDegree);
int i;
for (i=0; i <= smaller.degree && i <= newDegree; i++){
newPoly.terms[i] = smaller.terms[i] + larger.terms[i];
}
for(int j=i; j <= newDegree; j++) {
newPoly.terms[j] = larger.terms[j];
}
return newPoly;
}
public Polynomial multiply(Polynomial other) throws NullPointerException {
// Effects: If other is null throws NullPointerException else
// returns the Polynomial this * other
if ((other.degree == 0 && other.terms[0] == 0) ||
(this.degree==0 && this.terms[0] == 0)) {
return new Polynomial();
}
Polynomial newPoly = new Polynomial(degree + other.degree);
newPoly.terms[degree + other.degree] = 0;
for(int i=0; i<=degree; i++) {
for (int j=0; j<= other.degree; j++) {
newPoly.terms[i+j] = newPoly.terms[i+j] + this.terms[i] * other.terms[j];
}
}
return newPoly;
}
At quick glance, looks like this is a problem
for(int i = 0; i < arrayList.size(); i++)
{
Polynomial polynomial = new Polynomial(arrayList.get(i), arrayList.get(i+1));
polynomialarraylist.add(polynomial);
System.out.println("coef" + arrayList.get(i));
System.out.println("degree" + arrayList.get(i+1));
i++;
}
You're doing i++ twice here.
Also, you posted WAY too much code. No one wants to read that much. You're just lucky that, assuming this is the problem, I happened to glance at that.
Also that will throw an arrayindexoutofboundserror since you're doing .get(i+1)
the constructor is set up the way it is because the get(i) gets you the coefficient and the i+1 gets you the degree from the arraylist parameter since when you call add, without those the arraylist contents would be off
THe constructor is suppose to take an Arraylist and put them inisde of an arraylist of polynomials. using the odds as the coefficient and the evens as the degrees of the polynomials.

Categories