I have to create an ADT to read a number of data and calculate the median of those data. The ADT consist in a MIN and a MAX heap.
The MinHeap class takes the numbers greaters or equal than the median.
public class MinHeap {
public double[] data;
public int Size;
public MinHeap(int size) {
data = new double[size];
Size = 0;
}
public double getMinimum(){
return this.data[0];
}
public boolean isEmpty() {
return (Size == 0);
}
private int getParentIndex(int nodeIndex) {
return (nodeIndex - 1) / 2;
}
public void insertu(double value) throws Exception {
if (Size == data.length)
throw new Exception("Heap's underlying storage is overflow");
else {
Size++;
data[Size - 1] = value;
siftUp(Size - 1);
}
}
public void siftUp(int nodeIndex) {
int parentIndex;
double tmp;
if (nodeIndex != 0) {
parentIndex = getParentIndex(nodeIndex);
if (data[parentIndex] > data[nodeIndex]) {
tmp = data[parentIndex];
data[parentIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
siftUp(parentIndex);
}
}
}
}`
The MaxHeapclass takes the numbers that are less or equal than the median.
public class MaxHeap{
public double [] _Heap;
public int _size;
public int tam=0;
public MaxHeap (int a){
_Heap = new double[a];
_size = _Heap.length;
for (int i = _Heap.length / 2 ; i >=0 ; i--) {
tam++;
maxHeapify(i);
}
}
private int parent(int pos)
{ return pos / 2; }
private int leftChild(int pos)
{ return (2 * pos); }
private int rightChild(int pos)
{ return (2 * pos) + 1; }
private void swap(int fpos,int spos) {
double tmp;
tmp = _Heap[fpos];
_Heap[fpos] = _Heap[spos];
_Heap[spos] = tmp;
}
private void maxHeapify (int i) {
int l = leftChild(i), r = rightChild(i), largest;
if(l < _size && _Heap[l] > _Heap[i]) {
tam+=2;
largest = l;
}
else largest = i;
if(r < _size && _Heap[r] > _Heap[largest]) {
largest = r;
tam+=2; }
if (largest != i) {
tam++;
swap(i, largest);
maxHeapify (largest); }
}
protected boolean isEmpty() { return _size == 0; }
protected void deleteMax() {
if (_size > 1) {
tam++;
maxHeapify(0);
double max = _Heap[0];
_size--;
swap(0, _size);
maxHeapify(0); }
else _size = 0;
}
protected double extractMax() {
maxHeapify(0);
return _Heap[0];
}
public void insert(double element)
{
_Heap[++tam] = element;
int current = tam;
while(_Heap[current] > _Heap[parent(current)])
{
swap(current,parent(current));
current = parent(current);
}
}
}`
And the ADT:
`import java.util.InputMismatchException;`
`import java.util.Scanner;`
public class ColaPrioridadMediana {
private MinHeap MIN;
private MaxHeap MAX;
private int size;
public ColaPrioridadMediana(int cap) {
if (cap%2==0){
MIN = new MinHeap(cap/2);
MAX = new MaxHeap(cap/2);
}
else{
MIN = new MinHeap((cap+1)/2);
MAX = new MaxHeap((cap+1)/2);
}
size = MAX.counter + MIN.Size;
}
public void insertar(double x) throws Exception{
if (x <= MAX.extractMax()){
if (MAX.counter > MIN.Size){
double d = MAX.extractMax();
MIN.insertu(d);
MAX.insert(x);
}
else{
MAX.insert(x);
}
}
else{
if (MIN.Size > MAX.counter){
double d = MIN.getMinimum();
MAX.insert(d);
MIN.data[0] = x;
MIN.siftUp(1);
}
else{
MIN.insertu(x);
}
}
}
public int getSize(){
return size;
}
public double getMediana() throws Exception{
if(MAX.counter==MIN.Size){return ((MAX.extractMax()+MIN.getMinimum())/2);}
else{
if (MAX.counter<MIN.Size){return MIN.getMinimum();}
else{return MAX.extractMax();}
}
}
public static void main(String[] args) throws NumberFormatException, Exception{
#SuppressWarnings("resource")
Scanner num=new Scanner(System.in);
ColaPrioridadMediana allNumbers=new ColaPrioridadMediana(10);
while(true){
System.out.print("Number:");
try{
String number=num.nextLine();
double d;
if(!number.isEmpty()){
allNumbers.insertar(Double.parseDouble(number));
}else{
d = allNumbers.getMediana();
System.out.println("The result is " + d);
System.out.println(allNumbers.MAX.extractMax());
System.out.println(allNumbers.MIN.getMinimum());
System.out.println(allNumbers.MAX.counter);
System.out.println(allNumbers.MIN.Size);
for (int i=0;i<allNumbers.MAX._Heap.length;i++){
System.out.println(allNumbers.MAX._Heap[i]);
System.out.println(allNumbers.MIN.data[i]);
}
System.exit(0);
}
}
catch(InputMismatchException e){
System.out.println("Not number");
}
}
}
}`
The MinHeap works, but the MaxHeap don't store any numbers, and prints only 0.0. I'm really stuck in here.
In java, using the Java Standard class PriorityQueue to simulate Max-Min heap is not a bad idea. It will reduce coding significantly.
public class MaxMinHeap{
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((x,y)->(y-x));
private void add(int val) {
if (maxHeap.size() == 0) {
maxHeap.add(val);
} else {
int maxTop = maxHeap.peek();
if (val <= maxTop) {
maxHeap.add(val);
} else {
minHeap.add(val);
}
if (maxHeap.size() - minHeap.size() > 1) {
minHeap.add(maxHeap.poll());
} else if (minHeap.size() - maxHeap.size() > 1) {
maxHeap.add(minHeap.poll());
}
}
}
private double findMedian() {
if(maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
}else if(maxHeap.size() == minHeap.size()) {
return ((double) maxHeap.peek() + minHeap.peek()) / 2;
}else {
return minHeap.peek();
}
}
}
Related
Basically it's a array list implementation and I need to time how long it takes to add elements to it, along with other features. I compiled it though and there's no output and I can't find the problem. I instantiate an array of objects in the class then defined a method add(E e) to add an element E using basic assignment. Then the ListDriver should populate the array using the add() method and print it, but again, no output.
public class MyArrayList<E> {
public Object array[];
public int size = 0;
private static final int INITIAL_CAPACITY = 100;
public MyArrayList() {
array = new Object[INITIAL_CAPACITY];
this.size = 0;
}
private boolean arrayFull() {
if (size == array.length)
return true;
else
return false;
}
private boolean remove(Object o) {
for (int i = 0; i < size; i++) {
if (array[i].getClass() == o.getClass()) {
remove(i);
return true;
}
}
return false;
}
private void resize(int i) {
if (i == 0) {
Object[] temp = new Object[array.length*2];
for (int j = 0; j < size; j++) {
temp[j] = array[j];
}
this.array = temp;
}
if (i == 1) {
Object[] temp = new Object[array.length/2];
for (int j = 0; j < size; j++) {
temp[j] = array[j];
}
this.array = temp;
}
}
public void add(E e) {
if (!arrayFull()) {
array[size] = e;
size++;
}
else if (arrayFull()) {
resize(0);
add(e);
}
}
public int size() {
return size;
}
private void clear() {
array = null;
}
private Object remove(int index) {
if (halfFull()) {
resize(1);
}
Object temp = array[index];
for (int i = index; i < size; i++) {
array[i] = array[i+1];
}
size--;
return temp;
}
private boolean halfFull() {
if (size < (array.length/4)) {
return true;
}
else return false;
}
public void add(int index, E element) {
if (!arrayFull()) {
for (int i = size-1 ; i >= index ; i--) {
array[i] = array[i+1];
}
array[index] = element;
size++;
}
else {
resize(0);
add(index, element);
}
}
public String toString() {
String list = new String();
for (int i = 0; i < size; i++) {
list += " " + array[i];
}
return list;
}
public static void main(String[] args) {
MyArrayList temp = new MyArrayList();
System.out.println(temp.size);
}
}
And the driver
public class ListTester {
public static void main(String[] args) {
int n = 100;
MyArrayList arrayList = new MyArrayList();
int[] array = new int[n];
for (int i = 0; i < array.length; i++) {
array[i] = (int)Math.random() *2*n +1;
}
long startTime = System.nanoTime();
for (int i = 0; i < arrayList.size(); i++) {
arrayList.add(array[i]);
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(arrayList);
System.out.println(duration);
}
}
I need to give the widest path from one chosen node to another in a self-generated graph. After this, I need to state the "bottleneck" or smallest weight on the computed path. As it is, I don't know where to start to find the bottleneck and I'm having trouble showing the path. Under the Graph class, in the printPath method, I am currently getting a StackOverflow Error from presumably infinite recursion, though I don't understand how its recurring infinitely in the first place. I've used some code from here: https://www.geeksforgeeks.org/printing-paths-dijkstras-shortest-path-algorithm/ with slight modification to find the largest path rather than the shortest as well renaming variables. I feel an error in said modification is most likely one source of the problem. Following is the output of my most recent test:
Enter a positive integer.
5
Node list: {1,2,3,4,5}
Edge list: {(2,3,17),(2,4,8),(3,5,3)}
Enter a source node.
1
Enter a destination node
5
Vertex: 1 --> 5
Distance: 20
Path: Exception in thread "main" java.lang.StackOverflowError
at Graph.printPath(Graph.java:104)
at Graph.printPath(Graph.java:104)
at Graph.printPath(Graph.java:104)
Here's my code so far. I've had my code in separate classes, so I apologize for any errors I may have made combining them to one file. I also apologize for the massive and messy block of code but I don't think there's anything here I can weed out before posting.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class Graph{
private ArrayList<Node> nodes = new ArrayList<Node>();
private ArrayList<Edge> edges = new ArrayList<Edge>();
private int[][] adjMatrix;
Graph(int numNodes, int weightBound, double probability){
ArrayList<Node> tempNodeList = new ArrayList<Node>(numNodes);
for(int i = 0; i < numNodes; i++) {
Node tempNode = new Node(i+1);
tempNodeList.add(tempNode);
}
this.nodes = tempNodeList;
Random rand = new Random();
for(int i = 0; i < numNodes; i++) {
for(int j = i+1; j < numNodes; j++) {
if(rand.nextInt((int)Math.round(1/probability)) == 0) {
Edge tempEdge = new Edge(rand.nextInt(5*numNodes-1)+1, nodes.get(i), nodes.get(j));
edges.add(tempEdge);
}
}
}
adjMatrix = new int[numNodes][numNodes];
for(int i = 0; i < edges.size(); i++) {
adjMatrix[edges.get(i).getNode(0).getID()-1][edges.get(i).getNode(1).getID()-1] = edges.get(i).getWeight();
adjMatrix[edges.get(i).getNode(1).getID()-1][edges.get(i).getNode(0).getID()-1] = edges.get(i).getWeight();
}
}
public void printGraph() {
System.out.print("Node list: {");
for(int i = 0; i < nodes.size(); i++) {
nodes.get(i).printNode();
if(i != nodes.size()-1) {
System.out.print(",");
}
}
System.out.println("}");
System.out.print("Edge list: {");
for(int i = 0; i < edges.size(); i++) {
edges.get(i).printEdge();
if(i != edges.size()-1) {
System.out.print(",");
}
}
System.out.println("}");
}
public void widestPath(int source, int dest){
int numVertices = adjMatrix[0].length;
int[] longestDists = new int[numVertices];
boolean[] inPath = new boolean[numVertices];
for(int i = 0; i < numVertices; i++) {
inPath[i] = false;
}
longestDists[source] = 0;
Node tempNode = nodes.get(source);
tempNode.setParent(-1);
nodes.set(source, tempNode);
for(int i = 1; i < numVertices; i++) {
int furthestNode = -1;
int longestDist = Integer.MIN_VALUE;
for(int index = 0; index < numVertices; index++) {
if(!inPath[index] && longestDists[index] > longestDist) {
furthestNode = index;
longestDist = longestDists[index];
}
}
inPath[furthestNode] = true;
for(int index = 0; index < numVertices; index++) {
int edgeWeight = adjMatrix[furthestNode][index];
if(edgeWeight > 0 && ((longestDist + edgeWeight) > (longestDists[index]))){
tempNode = nodes.get(index);
tempNode.setParent(furthestNode);
nodes.set(index, tempNode);
longestDists[index] = longestDist + edgeWeight;
}
}
}
printResult(source, longestDists, dest);
}
public void printResult(int source, int[] dists, int dest) {
System.out.println("Vertex: " + (source+1) + " --> " + (dest+1));
System.out.println("Distance: " + dists[dest]);
System.out.print("Path: ");
printPath(dest);
}
public void printPath(int dest) {
if(nodes.get(dest).getParent() == -1) {
return;
}
printPath(nodes.get(dest).getParent()); // StackOverflow here
System.out.print((dest+1) + " ");
}
}
public class Node {
private int ID;
private int distance = Integer.MIN_VALUE;
private int parent;
Node(int id){
this.ID = id;
}
public int getID() {
return this.ID;
}
public void printNode() {
System.out.print(this.ID);
}
public void setDist(int dist) {
this.distance = dist;
}
public int getDist() {
return this.distance;
}
public void setParent(int p) {
this.parent = p;
}
public int getParent() {
return this.parent;
}
}
public class Edge {
private int weight;
private ArrayList<Node> vertices = new ArrayList<Node>(2);
Edge(int weight){
this.weight = weight;
}
Edge(int weight, Node n1, Node n2){
this.weight = weight;
this.vertices.add(n1);
this.vertices.add(n2);
}
public int getWeight() {
return weight;
}
public void setNodes(Node n1, Node n2) {
this.vertices.set(0, n1);
this.vertices.set(1, n2);
}
public ArrayList<Node> getNodes(){
return vertices;
}
public void printEdge() {
System.out.print("(" + vertices.get(0).getID() + "," + vertices.get(1).getID() + "," + this.weight + ")");
}
public int otherNodeIndex(int ID) {
if(vertices.get(0).getID() == ID) {
return 1;
}else if(vertices.get(1).getID() == ID) {
return 0;
} else {
return -1;
}
}
public Node getNode(int index) {
return vertices.get(index);
}
}
public class Driver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = -1;
while(input <= 0) {
System.out.println("Enter a positive integer.");
input = sc.nextInt();
}
double probability = 0.25;
Graph gr = new Graph(input, input*5, probability);
gr.printGraph();
int source = -1;
int dest = -1;
while(source < 0 || source > input) {
System.out.println("Enter a source node.");
source = sc.nextInt()-1;
}
while(dest < 0 || dest > input) {
System.out.println("Enter a destination node");
dest = sc.nextInt()-1;
}
gr.widestPath(source, dest);
}
}
I'm having an issue with one of my methods findLargest(Comparable[ ] arr) in class FindLargest that's meant to return the largest element in an array.
Apparently, in class Lab5Main this method works fine with fractions, but I get a compilation error with dates. In the system print out command, I'm getting this error:
The method findLargest(Comparable[ ]) in the type FindLargest is not applicable for the arguments (MyDate[ ])
Here is the supposed program output:
The largest fraction is 9/4
The latest date is 18/8/2011
My codes are shown below:
public class Lab5Main {
public static void main(String[] args) {
// Fraction
Fraction fractions[] = new Fraction[3];
fractions[0] = new Fraction(1, 2);
fractions[1] = new Fraction(6, 11);
fractions[2] = new Fraction(9, 4);
System.out.println("The largest fraction is " + FindLargest.findLargest(fractions));
// MyDate
MyDate dates[] = new MyDate[3];
dates[0] = new MyDate(1898, 6, 9);
dates[1] = new MyDate(2003, 4, 1);
dates[2] = new MyDate(2011, 8, 18);
System.out.println("The latest date is " + FindLargest.findLargest(dates));
}
}
public class FindLargest {
public static <T extends Comparable<? super T>> T findLargest(T[] arr) {
if (arr.length == 0) {
return null;
}
T max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i].compareTo(max) > 0) {
max = arr[i];
}
}
return max;
}
public class Fraction implements Comparable<Fraction> {
private int num, denom;
public int gcd(int a, int b) {
if (a%b==0) {
return b;
}
return gcd(b, a%b);
}
public void reduce() {
int g = gcd(num, denom);
num = num / g;
denom = denom / g;
}
public Fraction(int n, int d) {
if (n==0) {
d=1;
}
if (d==0) {
n=1;
d=2;
}
if(d<0) {
n=-n;
d=-d;
}
num = n;
denom = d;
reduce();
}
public String toString() {
return num + "/" + denom;
}
#Override
public int compareTo(Fraction f) {
// Fraction f = (Fraction) obj;
if (Math.abs(value() - f.value()) < 0.00001) {
return 0;
}
if (value() > f.value()) {
return 1;
}
return -1;
}
public int compareTo(Object obj) {
Fraction f = (Fraction) obj;
if (Math.abs(value() - f.value()) < 0.00001) {
return 0;
}
if (value() > f.value()) {
return 1;
}
return -1;
}
}
public class MyDate implements Comparable<MyDate> {
private int year, month, day;
public MyDate(int z, int y, int x) {
if (z<1000 || z>3000) {
z = 2000;
}
if (y<1 || y>12) {
y = 1;
}
if (x<1 || x>31) {
x = 1;
}
day = x;
month = y;
year = z;
}
public String toString() {
return day + "/" + month + "/" + year;
}
#Override
public int compareTo (MyDate date){
// MyDate date = (MyDate) obj;
int diffYear = year - date.year;
if (diffYear < 0) {
return -1;
}
else if (diffYear > 0) {
return 1;
}
int diffMonth = month - date.month;
if (diffMonth < 0) {
return -1;
}
else if (diffMonth > 0) {
return 1;
}
int diffDay = day - date.day;
if (diffDay < 0) {
return -1;
}
else if (diffDay > 0) {
return 1;
}
return 0;
}
}
The issue is one of raw-types and generics. Comparable is a generic interface, but you are implementing it with a raw-type and you are using it with raw-types. You should fix that. Something like,
public static <T extends Comparable<? super T>> T findLargest(T[] arr) {
if (arr.length == 0) {
return null;
}
T max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i].compareTo(max) > 0) {
max = arr[i];
}
}
return max;
}
will ensure that you call findLargest with a generic type T that can be compared with itself and all of its' superclasses. You should also change Fraction and MyDate. Something like,
public class Fraction implements Comparable<Fraction> {
// ...
#Override
public int compareTo(Fraction f) {
if (Math.abs(value() - f.value()) < 0.00001) {
return 0;
}
if (value() > f.value()) {
return 1;
}
return -1;
}
}
And MyDate similarly. I would recommend you always use the #Override annotation when you intend to override a method.
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.
It seems that this calculator works for all other cases, except cases like this:
(2*3^4)
It does not return 162, instead, it returns 0.0.
I identified that the error must be from the method public static double operation, since the default return statement is 0.0
Here is the code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StackC<Item> implements Stack<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack
public StackC() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4)
resize(a.length/2);
return item;
}
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
return a[N-1];
}
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
public ReverseArrayIterator() {
i = N;
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
//---------------------------------------------------------------------
public static void main(String[] args) {
StackC<String> Operator = new StackC<String>();
StackC<Double> Values = new StackC<Double>();
while (!StdIn.isEmpty()) {
String token = StdIn.readString();
try {
Double x = Double.parseDouble(token);
Values.push(x);
}
catch(NumberFormatException nFE) {
}
if (token.equals("("))
Operator.push(token);
if (token.equals(")"))
{
if (Operator.peek() != "(")
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
Operator.pop();
}
if(token.equals("*") || token.equals("+") || token.equals("/") || token.equals("-") || token.equals("^") )
{
if(!Operator.isEmpty())
{
String prev = Operator.peek();
int x = comparePrecedence(token, Operator.peek()); // You need to compare precedence first
if(x == -1 || x == 0)
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
}
Operator.push(token);
}
}
while(!Operator.isEmpty())
{
String prev = Operator.peek();
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
System.out.println(Values.pop());
}
public static double operation(String operator, double a, double b) {
if (operator.equals("+"))
return a + b;
else if (operator.equals("-"))
return a - b;
else if (operator.equals("*"))
return a * b;
else if (operator.equals("/"))
return a / b;
else if (operator.equals("^"))
return Math.pow(a,b);
return 0.0;
}
public static int comparePrecedence(String x, String y)
{
int val1 = 0;
int val2 = 0;
if(x.equals("-"))
val1 = 0;
if(y.equals("-"))
val2 = 0;
if(x.equals("+"))
val1 = 1;
if(y.equals("+"))
val2 = 1;
if(x.equals("/"))
val1 = 2;
if(y.equals("/"))
val2 = 2;
if(x.equals("*"))
val1 = 3;
if(y.equals("*"))
val2 = 3;
if(x.equals("^"))
val1 = 4;
if(y.equals("^"))
val2 = 4;
if(val1 > val2)
return 1;
else if(val2 > val1)
return -1;
else
return 0;
}
}
Everything above the dotted line was given via the professor, and is not the problem for the code.
StdIn is simply a method that reads inputs.