Implementation of queue in Java - java

I am just curious, i have a class that implements a queue and it currently has one item... I am curious as to where would be the most efficient or cleanest location to initialize other items that i wish to add to the queue... This is part of an assignment so please provide an explanation and not just answer! thanks in advance... Here is the class i built...
import java.util.*;
public class Queue<T> extends Node<T> {
private LinkedList<T> list;
// Queue constructor
public Queue() {
// Create a new LinkedList.
list = new LinkedList<T>();
}
//check if empty
public boolean isEmpty() {
return (list.size() == 0);
}
//add items to queue
public void enqueue(Object item) {
// Append the item to the end of our linked list.
list.add((T) item);
}
//remove items from queue
public T dequeue() {
T item = list.get(1);
list.remove(1);
// Return the item
return item;
}
//check top item
public T peek() {
return list.get(1);
}
//check size of queue
public int size() {
return list.size();
}
}

This is how you write a queue:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Queue;
import java.util.*;
/**
*
* #author Madhurlucky
*/
public class arrayQueue {
public static int[] Queue;
public static int len, front, rear, size;
public arrayQueue(int n) {
len = 0;
size = n;
front = -1;
rear = -1;
Queue = new int[size];
}
public boolean isEmpty() {
return front == -1;
}
public boolean isFull() {
return (front == 0 && rear == size - 1);
}
public int getsize() {
return len;
}
public void insert(int i) {
if (rear == -1) {
rear = front = 0;
Queue[rear] = i;
} else if (rear + 1 >= size) {
System.out.println("OverFlow Queue");
} else if (rear + 1 < size) {
Queue[++rear] = i;
}
len++;
}
public int remove() {
int x = -99;
if (front != -1) {
x = Queue[front];
if (front == rear) {
front = rear = -1;
} else if (front < rear) {
front += 1;
}
len--;
}
return x;
}
/* Function to check the front element of the queue */
public int peek() {
if (isEmpty()) {
throw new NoSuchElementException("Underflow Exception");
}
return Queue[front];
}
public void display() {
System.out.print("\nQueue = ");
if (len == 0) {
System.out.print("Empty\n");
return;
}
for (int i = front; i <= rear; i++) {
System.out.print(Queue[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Array Queue Test\n");
System.out.println("Enter Size of Integer Queue ");
int n = scan.nextInt();
/* creating object of class arrayQueue */
arrayQueue q = new arrayQueue(n);
/* Perform Queue Operations */
char ch;
do {
System.out.println("\nQueue Operations");
System.out.println("1. insert");
System.out.println("2. remove");
System.out.println("3. peek");
System.out.println("4. check empty");
System.out.println("5. check full");
System.out.println("6. size");
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("Enter integer element to insert");
try {
q.insert(scan.nextInt());
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
break;
case 2:
try {
System.out.println("Removed Element = " + q.remove());
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
break;
case 3:
try {
System.out.println("Peek Element = " + q.peek());
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
break;
case 4:
System.out.println("Empty status = " + q.isEmpty());
break;
case 5:
System.out.println("Full status = " + q.isFull());
break;
case 6:
System.out.println("Size = " + q.getsize());
break;
default:
System.out.println("Wrong Entry \n ");
break;
}
/* display Queue */
q.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
} while (ch == 'Y' || ch == 'y');
}
}

Related

BubbleDown function(min heap) not working

I have generated a minheap to this file but I think something I have missed but I can't identify what are the things I have missed. I have missed something on --private void bubbleDown() { }-- section but I can't find what are the things missed by me.
private int default_size = 100; // how big the heap should be
private T[] array;
private int size;
public Heap() {
#SuppressWarnings("unchecked")
T[] tmp = (T[]) (new Comparable[default_size]);
array = tmp;
size = 0;
}
boolean isRoot(int index) { return (index == 0); }
int leftChild(int index) { return 2 * index + 1; }
int parent(int index) { return (index - 1) / 2; }
int rightChild(int index) { return 2 * index + 2; }
T myParent(int index) { return array[parent(index)]; }
T myLeftChild(int index) { return array[leftChild(index)]; }
T myRightChild(int index) { return array[rightChild(index)]; }
boolean hasLeftChild(int i) { return leftChild(i) < size-1; }
boolean hasRightChild(int i){ return rightChild(i) < size-1; }
private void swap(int a, int b) {
T tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
public boolean isEmpty() { return (size == 0); }
/* adding heap */
public void add(T value) {
if(size == default_size) throw new IllegalStateException("Full array");
array[size++] = value;
bubbleUp();
}
public void bubbleUp() {
if(size == 0) throw new IllegalStateException("Shape error");
int index = size - 1;
while(!isRoot(index)) {
if(myParent(index).compareTo(array[index]) <= 0) break;
/* else part */
swap(parent(index), index);
index = parent(index);
}
}
/* removing */
public T remove() {
if(isEmpty()) return null;
T res = array[0]; /* root */
array[0] = array[size-1];
size --;
bubbleDown();
return res;
}
// i think this section having wrong something
private void bubbleDown() {
int parent = 0;
int leftChild = 2*parent + 1;
int rightChild = 2*parent + 2;
int choice = compareAndPick(leftChild, rightChild);
while (choice != -1)
{
swap(choice, parent);
parent = choice;
choice = compareAndPick(2*choice+1, 2*choice+2);
}
}
private int compareAndPick(int leftChild, int rightChild)
{
if (leftChild >= default_size || array[leftChild] == null) return -1;
if (array[leftChild].compareTo(array[rightChild]) <= 0 || (array[rightChild] == null))
return leftChild;
return rightChild;
}
public void show() {
for(int i=0; i<size; i++)
System.out.print(array[i] + " ");
System.out.println("=======");
}
public static void main(String [] args) {
Heap<Integer> heap = new Heap<Integer>();
for(int i=0; i<10; i++) {
heap.add((Integer)(int)(Math.random() * 100));
heap.show();
}
System.out.println("You should see sorted numbers");
while(!heap.isEmpty()) {
System.out.print(heap.remove());
System.out.print(" ");
heap.show();
}
System.out.println();
}
}
this code used generics and min heap functions.. i need to identify what is the wrong thing did by me on bubbleDown() section
Explanation
The bubbleDown() method is not a different way to insert a node and move it to it's correct position in the Heap. When bubbleDown() is called it's job is to Heapify the Binary Tree from any state. So your attempt to write the method just by changing the condition from the bubbleUp() method isn't gonna help you.
Extra
Here is a video that can give you the idea of how bubbleDown is supposed to work.

Circular queue array implementation

Im trying to create a waiting list which will hold names of customers in a static array when the main array is full.and When the main array gets an EMPTY slot the first customer in the waiting list array will fill up the EMPTY slot of main array and the added element will be removed Im trying to create this using circular queue implementation.following the FIFO(First in first out) system
This is the circular queue implementation I have come up with
public class CQueue {
int SIZE = 4;
int front, rear;
int items[] = new int[4];
void initialize (String[]task) {
for (int i = 0; i < task.length; i++) {
task[i] = "FULL";
}
}
CQueue() {
front = -1;
rear = -1;
}
boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
if (front == rear + 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (front == -1)
front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
System.out.println("Inserted " + element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
return (element);
}
}
void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
System.out.println("Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE)
System.out.print(items[i] + " ");
System.out.println(items[i]);
System.out.println("Rear -> " + rear);
}
}
This the delete method which will take user input to delete the element from task array and add the first come element of queue.
void deleteArr(String task[]) {
CQueue q = new CQueue();
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
int element = items[front];
task[NUM]=Integer.toString(element);
q.deQueue();
q.display();
}
The main method
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue();
q.initialize(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
while (true) {
q.deleteArr(task);
for (int j = 0; j < task.length; j++) {
System.out.println(task[j]);
}
}
}
I am stuck on how to add the queue element to the task array when a task array is deleted
I'd recommend you to check if front>=0 in deteleArr function. Also you should use the queue instance defined in main, and not a new instance:
void deleteArr(String task[]) {
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
if(front>=0) {
task[NUM]=Integer.toString(items[front]);
}
this.deQueue();
}
If you want, you can use the following display queue function:
void display() {
int i;
System.out.println("Print queue");
System.out.println("===========");
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
for (i = front; i <= rear; i++) {
System.out.println("item["+i+"]: " +items[i]);
}
System.out.println("Rear -> " + rear);
}
System.out.println("============");
}
And you can use this another function to display the task array:
public static void printTaskArray(String task[]) {
System.out.println("Print task[]");
System.out.println("============");
if (task.length==0) {
System.out.println("Empty task");
} else {
for (int j = 0; j < task.length; j++) {
System.out.println("task["+j+"]: "+task[j]);
}
}
System.out.println("============");
}
With this encapsulation you can change your main as follows:
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue ();
q.initialize(task);
printTaskArray(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
printTaskArray(task);
q.display();
while (true) {
q.deleteArr(task);
printTaskArray(task);
q.display();
}
}
I hope this help you.

How do you implement Comparable in this situation?

I've looked up examples as to how Comparable works and I somewhat understand how it would work but I don't know how I would use it in this situation.
I have an ArrayObject class implements Comparable and imported java.util.*; I also have an ArrayObjectDriver class that is a main method that calls upon methods I've coded in the ArrayObject class. One of the methods that it has to be able to do is to sort the array of objects in the main method. I know you have to use something with .compareTo but I'm not sure how I would do that in the ArrayObject class and call on it in the driver.
EDIT: ArrayObject code
public class ArrayObject implements Comparable
{
private Object[] arr;
private int actualSize;
ArrayObject()
{
arr = new Object[10];
actualSize = 0;
}
ArrayObject(int size)
{
arr = new Object[size];
actualSize = 0;
}
public void add(Object obj)
{
if(actualSize>=arr.length)
expandArray();
arr[actualSize]=obj;
actualSize++;
}
public void expandArray()
{
int newSize = arr.length*2;
Object[] biggerList = new Object[newSize];
for(int i=0; i<arr.length; i++)
{
biggerList[i] = arr[i];
}
arr = biggerList;
}
public void add(Object obj, int index)
{
if(index<actualSize)
{
shiftRight(index);
arr[index]=obj;
actualSize++;
}
// index is between [0 and actualSize)
}
private void shiftRight(int start)
{
for(int i=actualSize; i>start; i--)
{
arr[i] = arr[i-1];
}
arr[start]=null;
}
private void shiftLeft(int start)
{
for(int i=start; i<actualSize-1; i++)
{
arr[i] = arr[i+1];
}
arr[actualSize-1]=null;
}
public Object remove(int index)
{ // returning the object you are removing
// ("the", "is", "are")
if(index>=0&&index<actualSize)
{
Object obj = arr[index];
arr[index] = null;
// arr[index] = arr[actualSize-1];
// what to do about the null?
// Shift to the left by one
shiftLeft(index);
actualSize--;
// ("the", null, "are")
return obj;
}
return null;
}
public Object get(int index)
{
if(index>=0&&index<actualSize)
return arr[index];
return null;
}
public int sizeOfContainer()
{
return arr.length;
}
public int items()
{
return actualSize;
}
public boolean searchArray(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return true;
}
return false;
}
public int findObject(Object obj)
{
if(searchArray(obj))
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return i;
}
}
return -1;
}
public boolean isItEmpty()
{
if(actualSize == 0)
return true;
return false;
}
public int removeSearch(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
{
remove(i);
return i;
}
}
return -1;
}
public void clearArray()
{
for(int i=0; i<actualSize; i++)
arr[i] = remove(i);
}
public void printArr()
{
System.out.println("Array Size: " + actualSize);
for(int i=0; i<actualSize; i++)
{
System.out.println(arr[i]);
}
}
}
ArrayObjectDriver code
public class ArrayObjectDriver
{
private static Scanner scanner;
public static void main(String[] args)
{
scanner = new Scanner(System.in);
ArrayObject array = new ArrayObject();
int selection = selectionMenu();
while(selection > 0)
{
if(selection == 1)
{
System.out.println("Enter your object: ");
String str = scanner.next();
array.add(str);
}
else if(selection == 2)
{
System.out.println("Enter your object: ");
String str = scanner.next();
System.out.println("Enter location: ");
int n = scanner.nextInt();
array.add(str, n);
}
else if(selection == 3)
{
System.out.println("Enter location: ");
int n1 = scanner.nextInt();
array.remove(n1);
}
else if(selection == 4)
{
System.out.println("Enter object: ");
String str = scanner.next();
int i = array.removeSearch(str);
System.out.println("Object removed at index " + i);
}
else if(selection == 5)
{
array.clearArray();
System.out.println("Cleared Array");
}
else if(selection == 6)
{
System.out.println("Enter object: ");
String str = scanner.next();
boolean result = array.searchArray(str);
System.out.println("The object was found: " + result);
}
else if(selection == 7)
{
boolean result = array.isItEmpty();
System.out.println("It is empty: + result);
}
else if(selection == 8)
{
array.expandArray();
int i = array.sizeOfContainer();
System.out.println("The new size of the array is: " + i);
}
else if(selection == 9)
{
System.out.println("Enter object: ")
String str = scanner.next();
int i = array.findObject(str);
System.out.println("The object was found at index " + i);
}
else if(selection == 10)
array.printArr();
else if(selection == 11)
{
}
else if(selection == 12)
System.exit(0);
System.out.println("");
selection = selectionMenu();
}
}
private static int selectionMenu()
{
System.out.println("Menu: ");
System.out.println("1. Add object to the end of the list");
System.out.println("2. Add object at a specific location");
System.out.println("3. Remove specific object at a location");
System.out.println("4. Remove specific object that matches name");
System.out.println("5. Empty the array");
System.out.println("6. See if the array contains a certain object");
System.out.println("7. See if the array is empty");
System.out.println("8. Expand your array");
System.out.println("9. Search for an item");
System.out.println("10. Print array");
System.out.println("11. Sort array");
System.out.println("12. Exit");
System.out.println("Enter option: ");
int optionNumber = scanner.nextInt();
return optionNumber;
}
}
Just make a sort method in your ArrayObject class and you can call that when user enters 11.
In ArraysObject:
public void sort(){
Arrays.sort(arr); //This is all you have to call to sort your array arr
}
In your ArrayObjectDriver:
else if(selection == 11)
{
array.sort();
}
The Arrays class has useful methods for searching, manipulating, and sorting arrays including Arrays.sort and Arrays.binarySearch.

I'm trying to access a Private Variable from a sub class

Here is the beginning of my code from my sub class RECORD.
class Record {
private int shares;
private int pricePerShare;
// constructor
Record(int sharesNewValue, int pricePerShareNewValue) {
shares = sharesNewValue;
pricePerShare = pricePerShareNewValue;
}
// inspectors
public int getShares() {
return shares;
}
public int getPricePerShare() {
return pricePerShare;
}
// modifiers
public void setShares(int sharesNewValue) {
shares = sharesNewValue;
}
public void setPricePerShare(int pricePerShareNewValue) {
pricePerShare = pricePerShareNewValue;
}
}
And I want to access the value of shares in my main method that is in a different class.I have the RECORD class linked to another subclass named QUEUE. And in my main method, I have a link to QUEUE with this:
class Lab04a {
public static Queue Q = new Queue();
}
Later on in the code, I need to subtract an int value from the SHARES variable in the Record class, but because that is of type Record, I have no clue how to do this!
I'm not sure if I was clear enough when explaining this, should you have any further questions I'll be more than happy to reply.
Thank you.
Due to my inability to coherently state what I'm trying to accomplish in this lab assignment, I'll just post my other two classes in their entirety:
class Queue {
private int count; // number of elements in the queue
private int head; // index of head element, -1 if queue is empty
private int tail; // index of tail element, -1 if queue is empty
private int MAXSIZE = 1; // Physical size of the queue. DO NOT CHANGE!
private Record[] array; // circular array to store the elements of the queue
// constructor
Queue() {
count = 0;
head = -1;
tail = -1;
array = new Record[MAXSIZE];
}
// inspectors
public boolean empty() {
// Returns true if the queue is empty. Otherwise returns false.
return (count != 0);
}
public int size() {
// Returns the number of elements in the queue
return count;
}
public Record front(){
// Returns the head element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count == 0)
return new Record(-1, -1);
else
return array[head];
}
public Record rear(){
// Returns the tail element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count ==0)
return new Record(-1, -1);
else
return array[tail];
}
public String toString() {
// Returns the elements of the queue
String str = "< ";
int h = head;
for (int i = 0; i < count; i++){
str += "(" + array[h].getShares() + ", " + array[h].getPricePerShare() + ") ";
h = (h+1) % MAXSIZE;
}
str += ">";
return str;
}
// modifiers
public boolean dequeue() {
// Removes the head element of the queue.
if (count == 0)
return false;
if (count == 1) {
count = 0;
head = -1;
tail = -1;
}
if (count > 1){
head = (head + 1) % MAXSIZE;
count--;
}
return true;
}
public void enqueue(Record element) {
// Enqueues element to the tail of the queue.
//if max size is reached, it doubles the size to allow for more values
if (count == MAXSIZE) {
Record[] array2 = new Record[MAXSIZE * 2];
for (int i = 0; i < count; i++) {
array2[i] = array[i];
}//closes for loop
array = array2;
MAXSIZE *= 2;
}
tail = (tail + 1) % MAXSIZE;
array[tail] = element;
if (count == 0)
head = tail;
count++;
}//close enqueue method
}//closes class
And then here is my MAIN parent class:
class Lab04a {
public static Queue Q = new Queue(); // creates global object
public static Record R = Record;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int option, buyPrice, buyShares, sellPrice, sellShares, totalShares, totalValues, totalSellPrice;
option = 0;
totalShares = 0;
totalValues = 0;
Queue Q2 = Q;
while (option != 3) {
System.out.print("Enter option (1:buy, 2:sell, 3:quit): ");
option = scan.nextInt();
if (option == 1) {
System.out.print("Enter shares to buy and price per share: ");
buyShares = scan.nextInt();
buyPrice = scan.nextInt();
Record r = new Record(buyShares, buyPrice);
Q.enqueue(r);
totalShares = totalShares + buyShares;
totalValues = totalValues + (buyShares * buyPrice);
}// ends if
if (option == 2) {
System.out.print("Enter shares to sell and price per share: ");
sellShares = scan.nextInt();
sellPrice = scan.nextInt();
totalSellPrice = sellPrice * sellShares;
if (sellShares > totalShares) {
System.out.println("You do not own enough shares for this sale.");
}
for (int i = sellShares; i > 0; ) {
if (sellShares == Q.front().getShares()) {
i -= Q.front().getShares();
Q.dequeue();
}
if (sellShares < Q.front().getShares()){
Record minus;
minus = Q.front() - sellShares;
Q.front().setShares(minus);
Q.front().setShares(Q.front().getShares());
i -= sellShares;
}
}
}// ends if
// Prints content of Queue
System.out.println("Queue: " + Q.toString());
System.out.println("Total Shares: " + totalShares);
System.out.println("Total Shares Value: $" + totalValues);
System.out.println();
}// ends while loop
System.out.println(Q.toString());
}// ends main method
}
If I understand your question, you can add accessor and mutator methods (or getters and setters)
private int shares;
private int pricePerShare;
public int getShares() {
return shares;
}
public void setShares(int shares) {
this.shares = shares;
}
public int getPricePerShare() {
return pricePerShare;
}
public void setPricePerShare(int pricePerShare) {
this.pricePerShare = pricePerShare;
}
Edit
To use it,
Record record = Q.front(); // <-- I assume your Q contains Record(s).
if (record.getShares() >= sellShares) {
record.setShares(record.getShares() - sellShares); // <-- for example
}
Make sure Q.front() is a method that returns a Record.
If that is true, you should be able to use the line
Q.front().setShares(Q.front().getShares()-MINUS_VALUE))

Java Object [] sorting

I am trying to sort an array of created objects each time an object is added. I wrote a compareTo method, and it is printing out each line, but throws an exception when I try to sort it. I am initializing an Element[] of 99 elements(maxLen), then using topIndex as a counter to find the "real" length. A scanner is used to get user input to create the Element. EDIT-- I added the full code.
import java.util.Arrays;
import java.util.Scanner;
public class mainmenu {
static Element[] data = new Element[100];
static int maxLen= 99;
static int topIndex= -1;
#SuppressWarnings("rawtypes")
public static void main(String[] args){
menu();
}
public static void menu(){
boolean leave = true;
Scanner in = new Scanner(System.in);
while(leave){
//loop. unless value is 1-7, keeps recycling
System.out.println("Please select a menu option: ");
System.out.println("'1'- enque ");
System.out.println("'2'- deque");
System.out.println("'3'- peek");
System.out.println("'4'- display");
System.out.println("'5' empty queue");
System.out.println("'6'- check if the queue is empty");
System.out.println("'7' to exit the program");
String select = in.next();
if ((select.equals("1") || select.equals("2")|| select.equals("3")|| select.equals("4")||
select.equals("5")|| select.equals("6")|| select.equals("7")))
leave = callMethods(select );
else{
System.out.println("Please enter a valid menu option.");
}
}
}
public static boolean callMethods(String select )
{
boolean leave= true;
int sel = Integer.parseInt(select);
switch(sel){
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
empty();
break;
case 6:
if( isEmpty()){
System.out.println("The structure is empty");
}
else{
System.out.println("The structure is not empty.");
}
break;
case 7:
System.out.println("Bye!");
leave = false;
}
return leave;
}
public static void enqueue(){
boolean isInt = false;
String st = null;
int index = 0;
Scanner in = new Scanner(System.in);
while(!isInt){ //loop continues until input is an integer type
System.out.println("Please enter a priority level for this element");
st = in.next();
if (isInteger(st) == true){// calls method to check if value is integer
index = Integer.parseInt(st);//parses the string into a integer
isInt = true;
}
else //if value isnt integer, try again
System.out.println("Invalid Input.");
}
System.out.println("Please enter the string of information.");
String info = in.next();
Element e = new Element(info, index);
if (topIndex == maxLen){
System.out.println("Data Structure is full.");
}
else if (isEmpty()){
data[0] = e;
topIndex++;
}
else {
topIndex++;
data[topIndex]=e;
System.out.println("Added "+ e.getPriority() + " at "+ e.getInfo());
System.out.println(topIndex);
Arrays.sort(data);
}
}
private static boolean isInteger(String s) {
//checks to see if string can be parsed as an integer.
try{
Integer.parseInt(s);
return true;
}
catch( Exception e ){
return false;
}
}
public static void dequeue(){
if(isEmpty()){
System.out.println("The structure is empty.");
}
else{
Element e = data[topIndex];
System.out.println("Removing Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
--topIndex;
}
}
public static void peek(){
if (isEmpty()){
System.out.println("The structure is empty.");
}
else {
Element e = (data[0]);
System.out.println("Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
}
}
public static void display(){
System.out.println("topIndex " + topIndex);
if (topIndex==-1){
System.out.println("The structure is empty.");
}
else {
for(int i = 0; i <= topIndex; i++){
System.out.println("Index: " +i);
Element e = data[i];
System.out.println("Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
}
}
}
public static void empty(){
System.out.println("Erasing data.");
topIndex=-1;
}
public static boolean isEmpty(){
return (topIndex==-1);
}
}
And the Element class:
public class Element implements Comparable<Element> {
private String info;
private int index;
public Element ( String st, int ind) {
super();
this.info = st;
this.index= ind;
}
public String getInfo() {
return info;
}
public void setInfo(String st) {
this.info = st;
}
public int getPriority(){
return index;
}
public void setPriority(int pr){
this.index = pr;
}
public int compareTo(Element e) {
System.out.println(e.index+ ""+ e.info);
// if (!(e instanceof Element))
// throw new ClassCastException("An Element object expected.");
int ePriority = e.getPriority();
System.out.println(ePriority);
System.out.println(this.index);
int balls= this.index - ePriority;
System.out.println(balls);
return balls;
}
}
Arrays.sort requires all of the array elements to be non-null. You want to sort only the non-null part, so replace Array.sort(data) with Arrays.sort(data, 0, topIndex + 1).
Arrays.sort(Object[], int, int)
Do not modify compareTo to allow a null argument as others have suggested, because the contract of Comparable dictates that your implementation should throw NullPointerException.
Comparable.compareTo(T)
You have given Element[] array data to Array.sort() method which has size 100, but all of the element of data array are not initialized. Hence a call such as e.getPriority(); will result in NullPointerException as e is null. Initialize all of the element of data array first.
for(int i=0 ; i< data.length; i++)
e = new Element(info, index); // replace with relevant info and index of your contest
Use Arrays.sort(Object[] array, int fromIndexInclusive, int toIndexExclusive) to sort parts of an array if needed:
Arrays.sort(data, 0, topIndex+1);
From your error description I would guess the Element object is getting null.
As per your comment
It will throw the Element object expected exception I wrote in. If I comment out the throw declaration in the compareTo method, I get a null pointer exception.
if (!(e instanceof Element))
throw new ClassCastException("An Element object expected.");
The above statement will throw the exception only the object e is NULL
When doing a comparison, you're deciding if one object outranks another by some arbitrary condition.
I notice that you don't check if the object you're comparing against is null - you should do that.
public int compareTo(Element e) {
if(e == null) {
return this.index;
} else {
// rest of your logic goes here
}
}

Categories

Resources