I am not sure if I am implementing the insert or append correctly but I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
-1 at AListInt.insert(AListInt.java:81) // listArray[i+1] = listArray[i]; at ListTest.main(ListTest.java:52) // list.insert(i);
Also I cannot use java.util.ArrayList
Here is the code and classes for it:
class:
public class AListInt {
int [] listArray;
int listSize;
int curr; // current position
AListInt() {
listSize = 0;
// note that curr = -1 when listSize = 0
curr = -1;
listArray = new int [2];
}
public int getValue () throws DSException {
return listArray[curr];
//returns the value of current position
//throw exception when there are no elements in the list
}
public int length() {
return listSize;
//return # of elements in the list
}
public int currPos() {
return curr;
//return current position.
}
public void moveToPos ( int pos ) throws DSException {
curr = pos;
//move the current position to pos
//throw exception if pos is not a valid position
}
public void moveToStart () throws DSException {
curr = 0;
//move the current position to the start of the list
//throw exception if no elements are in the list
}
public void moveToEnd () throws DSException {
curr = listSize;
//move the current position to the end of the list
//throw exception if no elements are in the list
}
public void prev () throws DSException {
if(curr != 0)
{
curr--;
}
//move current position to the previous element
//throws exception if the previous position is not legal or
// if there are no elements in the list
}
public void next () throws DSException {
if(curr < listSize)
{
curr++;
}
//move current position to the next element
//throws exception if the next position is not legal or
// if there are no elements in the list
}
public void insert ( int item ) {
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
listArray[curr] = item;
listSize ++;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
}
listArray = temp;
// inserts item to the current position
// if not enough memory, double the size of listArray
}
public void append ( int item ) {
listArray[listSize++] = item;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
listArray = temp;
}
// inserts item to the end of the list
// if not enough memory, double the size of listArray
}
public int remove () throws DSException {
if((curr < 0)||(curr > listSize))
{
return -1;
}
int item;
item = listArray[curr];
for(int i = curr; i < listSize - 1; i++)
{
listArray[i] = listArray[i+1];
}
listSize --;
return item;
//removes the element at the current position
//returns the removed element
}
public void clear() {
listSize = 0;
curr = -1;
//reset size. Set current position to be -1
}
public boolean find ( int val ) {
for(int i = 0; i > listSize; i ++)
{
if(listArray[i] == val)
{
return true;
}
}
return false;
//searches for val in the list
//returns true if found and false if not found
}
public void print () {
System.out.print("<");
for(int i = 0; i < listSize; i++)
{
System.out.print(listArray[i]);
if(listSize == -1)
{
System.out.print("-1");
}
}
System.out.print(">");
//outprint the list
}
}
exception:
public class DSException extends Exception {
public DSException() {
}
public DSException(String msg) {
super(msg);
}
}
main:
public class ListTest {
public static void main ( String[] args ) {
try {
AListInt list = new AListInt();
list.print();
// test length()
System.out.println ( list.length() );
// test currPos()
System.out.println ( list.currPos() );
// insert some numbers
for ( int i = 0; i < 4; i++ ) {
list.append(i);
list.print();
}
list.moveToPos(0);
list.print();
list.moveToEnd();
list.print();
// test getValue()
System.out.println ( list.getValue() );
System.out.println ( "remove: " + list.remove() );
list.print();
list.moveToStart();
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
list.clear();
list.print();
list.clear();
list.print();
System.out.println ( "find 0 : " + list.find ( 0 ) );
for ( int i = 0; i < 4; i++ ) {
list.insert(i);
list.print();
}
for ( int i = 0; i < 5; i++ ) {
System.out.println ( "find " + i + " : " + list.find ( i ) );
list.print();
}
list.next();
list.print();
list.insert ( -9 );
list.print();
list.append ( -2 );
list.print();
list.moveToEnd();
list.insert ( -1 );
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
} catch ( DSException e ) {
e.printStackTrace();
}
}
}
You reading outside the Array. in
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
if i = listSize -1, then listArray[i+1] is listArray[listSize], which is out of bounds, since arrays go from 0 to length -1
EDIT:
But since listArray has an initial size of 2, and you double the size at each insert you get away with that. However, at the first insert curr is -1, and since the termination is i >= curr, the loop will be entered and you will read listArray[-1] (Out of bounds)
it's gotta be listArray[i]=listArray[i-1]
because you are shifting the position of listArray[i-1] to the position of listArray[i]
Related
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.
I have a nearly fully functional program but I am not able to format the output correctly. I am in desperate need of help as my project is past due already.
I am a student working on a program that reads in a simple text file and creates a graph object of nodes from the input file. I am then, supposed to use a heap class to build the nodes into a Min-heap. Finally I am supposed to call a heap sort method to sort the nodes (preferably in descending order)
I believe that my methods are correct and that my data is being correctly built into a min heap and is being correctly sorted. The only problem I am having is formatting the output which should be simple but for some reason isn't. The idea is this:
my graph object contains 2 arrayLists the first is the unordered node list that was created from the input text file. The second is a blank arrayList that I am trying to copy nodes one at a time.
I am trying to use a for loop or a while loop to first copy one single node into the empty ArrayList then call my build heap method to build a Min heap of only 1 element, then call my sort method to sort the heap of 1 element. Then, I want to copy in a second node and again build a min heap of 2 elements and then call my sort method on the 2 element heap. Then, copy in a third node and build the heap with 3 nodes, and then call the sort on the 3 element heap, and so on and so forth until all elements have been copied into the array list and the full heap is built and the sort method is called on all elements.
My 3 element test file looks like this:
~ val X Y Z
Xerxes 0 ~ ~ ~
York -1 ~ ~ ~
Zardoz 1 ~ ~ ~
My 6 element test file looks like this:
~ val A B C D E F
Alfa 4 ~ ~ ~ ~ ~ ~
Bravo 6 ~ ~ ~ ~ ~ ~
Charlie -3 ~ ~ ~ ~ ~ ~
Delta -6 ~ ~ ~ ~ ~ ~
Echo 0 ~ ~ ~ ~ ~ ~
Foxtrot 55 ~ ~ ~ ~ ~ ~
the output should look something like this:
Heaps:
X
YX
YXZ
HeapSort:
YXZ
XZY
ZXY
I am using several "test" files including one with 3 elements and one with 6 elements.
My classes are as follows:
import java.io.*;
public class DelivB {
File inputFile;
File outputFile;
PrintWriter output;
Graph g;
public DelivB( File in, Graph gr ) {
inputFile = in;
g = gr;
// Get output file name.
String inputFileName = inputFile.toString();
String baseFileName = inputFileName.substring( 0, inputFileName.length()-4 ); // Strip off ".txt"
String outputFileName = baseFileName.concat( "_out.txt" );
outputFile = new File( outputFileName );
if ( outputFile.exists() ) { // For retests
outputFile.delete();
}
try {
output = new PrintWriter(outputFile);
writeGraphInfo(output);
//System.out.println("=============================\n" + "testing testing testing Deliv B Class");
}
catch (Exception x ) {
System.err.format("Exception: %s%n", x);
System.exit(0);
}
//System.out.println( "DelivB: To be implemented");
//System.out.println("\nDeliv B Class ++++++++++++++++++++++++++++++++++");
}
public Graph getG() {
return g;
}
public void setG(Graph g) {
this.g = g;
}
/** Read the file containing the Strings, line by line, then process each line as it is read.
**/
public void writeGraphInfo( PrintWriter output ) {
try {
// output the graph information.
// I chose to output it to the console as well as the file for debugging purposes.
System.out.println( "\n\n=========================================================================\n\n");
System.out.println( g );
output.println( g );
}
catch (Exception x ) {
System.err.format("ExceptionInner: %s%n", x);
System.exit(0);
}
output.close();
}
}
// NEXT CLASS
//===================================================
import java.util.*;
// A node of a graph for the Spring 2018 ICS 340 program
public class Node {
String name;
String val; // The value of the Node
String abbrev; // The abbreviation for the Node
ArrayList<Edge> outgoingEdges;
ArrayList<Edge> incomingEdges;
public Node( String theAbbrev ) {
setAbbrev( theAbbrev );
val = null;
name = null;
outgoingEdges = new ArrayList<Edge>();
incomingEdges = new ArrayList<Edge>();
}
public String getAbbrev() {
return abbrev;
}
public String getName() {
return name;
}
public String getVal() {
return val;
}
public ArrayList<Edge> getOutgoingEdges() {
return outgoingEdges;
}
public ArrayList<Edge> getIncomingEdges() {
return incomingEdges;
}
public void setAbbrev( String theAbbrev ) {
abbrev = theAbbrev;
}
public void setName( String theName ) {
name = theName;
}
public void setVal( String theVal ) {
val = theVal;
}
public void addOutgoingEdge( Edge e ) {
outgoingEdges.add( e );
}
public void addIncomingEdge( Edge e ) {
incomingEdges.add( e );
}
}
//NEXT CLASS ==================================================
//import java.util.*;
// Edge between two nodes
public class Edge {
String label;
Node tail;
Node head;
public Edge( Node tailNode, Node headNode, String theLabel ) {
setLabel( theLabel );
setTail( tailNode );
setHead( headNode );
}
public String getLabel() {
return label;
}
public Node getTail() {
return tail;
}
public Node getHead() {
return head;
}
public void setLabel( String s ) {
label = s;
}
public void setTail( Node n ) {
tail = n;
}
public void setHead( Node n ) {
head = n;
}
}
//NEXT CLASS ===================================================
import java.util.*;
public class Heap
{
int heapSize;
Graph gr;
ArrayList<Node> unordered_nodelist;
ArrayList<Node> ordered_nodelist;
Node dummy = new Node("dummy node");
//constructor for heap object with the following attributes:
//a graph object and an int representing the size of an arraylist of nodes
public Heap(Graph g)
{
unordered_nodelist = g.getNodeList();
heapSize = unordered_nodelist.size();
ordered_nodelist = new ArrayList<Node>();
//for (int i = 0; i < heapSize; i++)
//ordered_nodelist.add(dummy);
//probably don't need this graph variable
gr = g;
}
//getters and setters
public ArrayList<Node> getUnordered_nodelist() {
return unordered_nodelist;
}
public void setUnordered_nodelist(ArrayList<Node> unordered_nodelist) {
this.unordered_nodelist = unordered_nodelist;
}
public ArrayList<Node> getOrdered_nodelist() {
return ordered_nodelist;
}
public void setOrdered_nodelist(ArrayList<Node> ordered_nodelist) {
this.ordered_nodelist = ordered_nodelist;
}
public int getHeapSize() {
return heapSize;
}
public void setHeapSize(int heapSize) {
this.heapSize = heapSize;
}
//heap methods
public int Parent(ArrayList<Node> A, int i)
{
//if (i == 1)
//return (Integer)null;
if (i%2 != 0)
return i/2;
else
return (i-1)/2;
}
public int Left(ArrayList<Node> A, int i)
{
//while (A.get(i).getVal() != null && A.get(i).getName() != null)
//{
//if (2*i < heapSize)
return (2*i)+1;
//else
//return (Integer)null;
//}
}
public int Right(ArrayList<Node> A, int i)
{
//if ((2*i)+1 < heapSize)
return 2*i+2;
//else
//return (Integer)null;
}
public void Heapify(ArrayList<Node> A, int i)
{
Node smallest;
Node temp;
int index;
int l = Left(A,i);
int r = Right(A,i);
while (A.get(i).getVal() != null && A.get(i).getName() != null)
{
if (l <= heapSize-1 && Integer.parseInt(A.get(l).getVal()) < Integer.parseInt(A.get(i).getVal()))
{
//left child is smaller
smallest = A.get(l);
index = l;
}
else
{
//parent node is smaller
smallest = A.get(i);
index = i;
}
if (r <= heapSize-1 && Integer.parseInt(A.get(r).getVal()) < Integer.parseInt(smallest.getVal()))
{
//right child is smaller
smallest = A.get(r);
index = r;
}
if (index != i)
{
//if the smallest element is not the parent node
//swap the smallest child with the parent
temp = A.get(i);
A.set(i, A.get(index));
A.set(index, temp);
//recursively call heapify method to check next parent/child relationship
Heapify(A, index);
}
}
}
//method to construct min heap from unordered arraylist of nodes
public void Build_min_Heap(ArrayList<Node> A)
{
for (int k = 0; k<A.size()-1; k++)
{
//while (A.get(k).getVal() != null && A.get(k).getName() != null)
//{
int i;
int heapSize = A.size();
for (i = (heapSize/2); i>=0; i--)
{
Heapify(A, i);
System.out.print(gr.toString2()+"\n");
}
//}
}
}
//decreases the value of a given node, used with insert method
public void heap_Decrease_Key(ArrayList<Node> A, int i, int key)
{
Node parent;
Node child;
Node temp;
if (key > i)
{
System.out.println("error key must be less than i");
//break;
}
A.get(i).setVal(Integer.toString(key));
while(i>0 && Integer.parseInt(A.get(Parent(A,i)).getVal()) > Integer.parseInt(A.get(i).getVal()) )
{
parent = A.get(Parent(A,i));
child = A.get(i);
temp = parent;
//take the child node and place it in the parent node's place
A.set(Parent(A,i), child);
//take the parent node and place it in the child node's place
A.set(i, temp);
}
}
//method to sort in descending order, a min heap
public void heap_Sort(ArrayList<Node> A)
{
Node temp;
for (int k = 0; k<A.size()-1; k++)
{
//while (A.get(k).getVal() != null && A.get(k).getName() != null)
//{
Build_min_Heap(A);
System.out.println(gr.toString2()+"\n");
for(int i = A.size()-1; i >= 1; i--)
{
//exchange a[1] with a[i]
temp = A.get(0);
A.set(0, A.get(i));
A.set(i, temp);
//decrement heapSize
heapSize--;
//recursive heapify call
Heapify(A, 0);
}
//}
}
}
public Node heap_Extract(ArrayList<Node> A)
{
Node min;
min = A.get(0);
A.set(0, A.get(heapSize-1));
//decrement heapSize
heapSize--;
Heapify(A, 0);
return min;
}
public void heap_Insert(ArrayList<Node> A, int key)
{
heapSize++;
A.get(heapSize-1).setVal(Integer.toString(2147483647));
heap_Decrease_Key(A, heapSize-1, key);
}
public String toString()
{
String s = "Graph g.\n";
//s += "Heaps: \n";
if ( ordered_nodelist.size() > 0 )
{
//for loop to traverse an ArrayList of Nodes
for(Node n : ordered_nodelist)
{
//output string to print each node's character abbreviation
String t = n.getAbbrev();
s = s.concat(t);
}
}
return s;
}
}
//NEXT CLASS =================================================
import java.util.*;
public class Heap
{
int heapSize;
Graph gr;
ArrayList<Node> unordered_nodelist;
ArrayList<Node> ordered_nodelist;
Node dummy = new Node("dummy node");
//constructor for heap object with the following attributes:
//a graph object and an int representing the size of an arraylist of nodes
public Heap(Graph g)
{
unordered_nodelist = g.getNodeList();
heapSize = unordered_nodelist.size();
ordered_nodelist = new ArrayList<Node>();
//for (int i = 0; i < heapSize; i++)
//ordered_nodelist.add(dummy);
//probably don't need this graph variable
gr = g;
}
//getters and setters
public ArrayList<Node> getUnordered_nodelist() {
return unordered_nodelist;
}
public void setUnordered_nodelist(ArrayList<Node> unordered_nodelist) {
this.unordered_nodelist = unordered_nodelist;
}
public ArrayList<Node> getOrdered_nodelist() {
return ordered_nodelist;
}
public void setOrdered_nodelist(ArrayList<Node> ordered_nodelist) {
this.ordered_nodelist = ordered_nodelist;
}
public int getHeapSize() {
return heapSize;
}
public void setHeapSize(int heapSize) {
this.heapSize = heapSize;
}
//heap methods
public int Parent(ArrayList<Node> A, int i)
{
//if (i == 1)
//return (Integer)null;
if (i%2 != 0)
return i/2;
else
return (i-1)/2;
}
public int Left(ArrayList<Node> A, int i)
{
//while (A.get(i).getVal() != null && A.get(i).getName() != null)
//{
//if (2*i < heapSize)
return (2*i)+1;
//else
//return (Integer)null;
//}
}
public int Right(ArrayList<Node> A, int i)
{
//if ((2*i)+1 < heapSize)
return 2*i+2;
//else
//return (Integer)null;
}
public void Heapify(ArrayList<Node> A, int i)
{
Node smallest;
Node temp;
int index;
int l = Left(A,i);
int r = Right(A,i);
while (A.get(i).getVal() != null && A.get(i).getName() != null)
{
if (l <= heapSize-1 && Integer.parseInt(A.get(l).getVal()) < Integer.parseInt(A.get(i).getVal()))
{
//left child is smaller
smallest = A.get(l);
index = l;
}
else
{
//parent node is smaller
smallest = A.get(i);
index = i;
}
if (r <= heapSize-1 && Integer.parseInt(A.get(r).getVal()) < Integer.parseInt(smallest.getVal()))
{
//right child is smaller
smallest = A.get(r);
index = r;
}
if (index != i)
{
//if the smallest element is not the parent node
//swap the smallest child with the parent
temp = A.get(i);
A.set(i, A.get(index));
A.set(index, temp);
//recursively call heapify method to check next parent/child relationship
Heapify(A, index);
}
}
}
//method to construct min heap from unordered arraylist of nodes
public void Build_min_Heap(ArrayList<Node> A)
{
for (int k = 0; k<A.size()-1; k++)
{
//while (A.get(k).getVal() != null && A.get(k).getName() != null)
//{
int i;
int heapSize = A.size();
for (i = (heapSize/2); i>=0; i--)
{
Heapify(A, i);
System.out.print(gr.toString2()+"\n");
}
//}
}
}
//decreases the value of a given node, used with insert method
public void heap_Decrease_Key(ArrayList<Node> A, int i, int key)
{
Node parent;
Node child;
Node temp;
if (key > i)
{
System.out.println("error key must be less than i");
//break;
}
A.get(i).setVal(Integer.toString(key));
while(i>0 && Integer.parseInt(A.get(Parent(A,i)).getVal()) > Integer.parseInt(A.get(i).getVal()) )
{
parent = A.get(Parent(A,i));
child = A.get(i);
temp = parent;
//take the child node and place it in the parent node's place
A.set(Parent(A,i), child);
//take the parent node and place it in the child node's place
A.set(i, temp);
}
}
//method to sort in descending order, a min heap
public void heap_Sort(ArrayList<Node> A)
{
Node temp;
for (int k = 0; k<A.size()-1; k++)
{
//while (A.get(k).getVal() != null && A.get(k).getName() != null)
//{
Build_min_Heap(A);
System.out.println(gr.toString2()+"\n");
for(int i = A.size()-1; i >= 1; i--)
{
//exchange a[1] with a[i]
temp = A.get(0);
A.set(0, A.get(i));
A.set(i, temp);
//decrement heapSize
heapSize--;
//recursive heapify call
Heapify(A, 0);
}
//}
}
}
public Node heap_Extract(ArrayList<Node> A)
{
Node min;
min = A.get(0);
A.set(0, A.get(heapSize-1));
//decrement heapSize
heapSize--;
Heapify(A, 0);
return min;
}
public void heap_Insert(ArrayList<Node> A, int key)
{
heapSize++;
A.get(heapSize-1).setVal(Integer.toString(2147483647));
heap_Decrease_Key(A, heapSize-1, key);
}
public String toString()
{
String s = "Graph g.\n";
//s += "Heaps: \n";
if ( ordered_nodelist.size() > 0 )
{
//for loop to traverse an ArrayList of Nodes
for(Node n : ordered_nodelist)
{
//output string to print each node's character abbreviation
String t = n.getAbbrev();
s = s.concat(t);
}
}
return s;
}
}
//NEXT CLASS ===============================================
import java.util.*;
public class Graph {
ArrayList<Node> nodeList;
ArrayList<Edge> edgeList;
public Graph() {
nodeList = new ArrayList<Node>();
edgeList = new ArrayList<Edge>();
}
public ArrayList<Node> getNodeList() {
return nodeList;
}
public ArrayList<Edge> getEdgeList() {
return edgeList;
}
public void addNode( Node n ) {
nodeList.add( n );
}
public void addEdge( Edge e ) {
edgeList.add( e );
}
//overridden toString() method to output both Nodes and the edges incumbent upon them
public String toString() {
String s = "Graph g.\n";
if ( nodeList.size() > 0 ) {
//for loop to traverse an ArrayList of Nodes
for( Node n : nodeList ) {
//output string to print basic labels for each node
String t = "\nNode " + n.getName() + ", abbrev " + n.getAbbrev() + ", value " + n.getVal() + "\n";
s = s.concat(t);
//for loop to traverse an ArrayList of outgoing Edges incumbent upon
//the given node in each iteration of the outer for loop
for(Edge a : n.getOutgoingEdges()){
//output String to print data about each outgoing edge
String q = n.getName() + " has edge to: " + a.getHead().getName() + " labeled: " + a.getLabel() + "\n";
s = s.concat(q);
}
//for loop to traverse an ArrayList of incomming Edges incumbent upon
//the given node in each iteration of the outer for loop
for(Edge a : n.getIncomingEdges()){
//output string to print data about each incomming edge
String r = n.getName() + " has edge from: " + a.getTail().getName() + " labeled: " + a.getLabel() + "\n";
s = s.concat(r);
}
}
s = s.concat("\n");
}
return s;
}
public String toString2()
{
String s = "Graph g.\n";
if ( nodeList.size() > 0 )
{
//for loop to traverse an ArrayList of Nodes
for( Node n : nodeList )
{
//output string to print each node's mnemonic
String t = n.getAbbrev();
s = s.concat(t);
}
}
return s;
}
}
//NEXT CLASS ==============================================
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
/** ProgramA simply reads a file containing rows of space-separated Strings,
** your assignment is to print out those strings interpreted as a graph.
**
** #author
** Mike Stein
**/
public class Prog340 extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L; // Keep Eclipse happy.
File inputFile;
File outputFile;
PrintWriter output;
JFileChooser fileChooser;
Graph g;
Heap h;
String[] comboBoxList; // For putting names in Combo Box
/** The main method instantiates a Prog340 class, which includes giving you a choice of things to do.
** The only one active now will be reading the graph file and having you parse it.
**
** #param args
** - Not used
**
** #throws FileNotFoundException
** - Thrown if the file selected is not found. Shouldn't happen with a FileChooser.
**/
public static void main(String[] args) throws FileNotFoundException {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
/** Create and show the GUI.
** For thread safety, this method should be invoked from the event-dispatching thread.
**/
private static void createAndShowGUI() {
// Create and set up the window
JFrame frame = new JFrame("Prog340");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new Prog340();
newContentPane.setOpaque(true);; // content panes must be opaque
frame.setContentPane(newContentPane);;
// Display the window.
frame.pack();
frame.setVisible(true);
}
/** The constructor creates a new ProgramA object, and sets up the input and output files.
**/
public Prog340() {
super( new BorderLayout() );
try {
// I like the colorful FileChooser.
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
System.out.println( "Look and feel set.");
}
catch (Exception e) { // exit on exception.
System.err.format("Exception: %s%n", e);
System.exit(0);
}
fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose a file");
// Start looking for files at the currect directory, not home.
fileChooser.setCurrentDirectory(new File("."));
inputFile = null;
g = new Graph();
// Select the action
comboBoxList = new String[8];
comboBoxList[0] = new String("prog340: Select file and read graph");
comboBoxList[1] = new String("Deliv A: Write Graph Info");
comboBoxList[2] = new String ("Deliv B: Run Heap methods on selected file");
comboBoxList[3] = new String ("Deliv C: TBD");
comboBoxList[4] = new String ("Deliv D: TBD");
comboBoxList[5] = new String ("Deliv E: TBD");
comboBoxList[6] = new String ("Deliv F: TBD");
comboBoxList[7] = new String ("exit");
JComboBox actionList = new JComboBox( comboBoxList );
actionList.setName("Action List");
actionList.setSelectedIndex(0);
actionList.addActionListener( this );
add( actionList, BorderLayout.PAGE_START );
}
// Listen to the Combo Box
public void actionPerformed( ActionEvent e ) {
JComboBox cb = (JComboBox)e.getSource();
String actionName = (String)cb.getSelectedItem();
int actionIndex = cb.getSelectedIndex();
switch( actionIndex ) {
case 0:{
g = new Graph();
readGraphInfo( g );
break;
}
case 1:
DelivA dA = new DelivA( inputFile, g );
break;
case 2:
{
int numElements = 1;
int j =0;
int k;
//rewritten switch statement case to make DelivB combo box work
g = new Graph();
readGraphInfo( g );
DelivB dB = new DelivB(inputFile, g);
h = new Heap(g);
System.out.println("unordered list: \n");
System.out.println(g.toString());
System.out.println("==========================================");
//h.Build_min_Heap(h.getOrdered_nodelist());
for (j = 0; j <= h.getHeapSize(); j++)
//while (j <= h.getHeapSize())
//for (Node n : h.getOrdered_nodelist())
{
//copy node elements from unordered arraylist to new empty arraylist
h.getOrdered_nodelist().add(h.getUnordered_nodelist().get(j));
System.out.println("unordered node list size is: " + h.getUnordered_nodelist().size()+ "\n");
System.out.println("ordered node list size is: " + h.getOrdered_nodelist().size());
System.out.println("\nvalue of j is: " + j + "\n");
System.out.println("Heaps: \n");
h.Build_min_Heap(h.getOrdered_nodelist());
System.out.println("after build heap call: \n" );
System.out.println(h.toString());
//System.out.println("\ngraph class toString method: \n");
//System.out.println(g.toString() + "\n");
//System.out.println(g.toString2());
System.out.println("HeapSort: \n");
h.heap_Sort(h.getOrdered_nodelist());
System.out.println("after heapsort call: \n");
System.out.println(h.toString());
j++;
//System.out.println("\n graph class toString method: \n");
//System.out.println(g.toString() + "\n");
//System.out.println(g.toString2());
//System.out.println("the"+j+"th element in the original array is: \n"+h.getOrdered_nodelist().get(j).getAbbrev());
//System.out.println("the"+j+"th element in the new array is: \n"+h.getUnordered_nodelist().get(j).getAbbrev());
//System.out.println("\n after build heap method call, the output is as follows: " + g.toString());
}
break;
}
case 3:
DelivC dC = new DelivC( inputFile, g );
break;
case 4:
DelivD dD = new DelivD( inputFile, g );
break;
case 5:
DelivE dE = new DelivE( inputFile, g );
break;
case 6:
DelivF dF = new DelivF( inputFile, g );
break;
case 7:
System.out.println( "Goodbye");
System.exit(0);
default:
System.out.println( "Invalid choice" );
System.exit(0);
}
}
/** Read the file containing the Strings, line by line, then process each line as it is read.
**/
public void readGraphInfo( Graph g ) {
try {
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
// Instantiate the selected input and output files.
inputFile = fileChooser.getSelectedFile();
System.out.println( "Chosen file = " + inputFile + "\n");
}
// read text file
Scanner sc = new Scanner( inputFile );
// First line special: It contains "~", and "val", and the nodes with the edges.
String firstLine = sc.nextLine();
String[] splitString = firstLine.split( " +" );
// Ignore first two fields of first line, Every other field is a node.
for ( int i = 2; i < splitString.length; i++ ) {
Node n = new Node( splitString[i] );
g.addNode( n );
}
// Every other line gives the name and value of the Node, and any edges.
int nodeIndex = 0;
ArrayList<Node> nodeList = g.getNodeList();
while ( sc.hasNextLine() ) {
String nextLine = sc.nextLine();
splitString = nextLine.split(" +");
Node n = nodeList.get( nodeIndex );
n.setName( splitString[0] );
n.setVal( splitString[1] );
for ( int i = 2; i < splitString.length; i++ ) {
if ( !splitString[i].equals("~") ) {
Node head = nodeList.get(i-2);
Edge e = new Edge( n, head, splitString[i] );
g.addEdge( e );
n.addOutgoingEdge( e );
head.addIncomingEdge( e );
}
}
nodeIndex++;
}
sc.close();
}
catch (Exception x) {
System.err.format("ExceptionOuter: %s%n", x);
}
}
}
I have a remove method in a Priority Queue class I created from scratch for an assignment. The priority queue I created is held in an array, with the index starting at 0. I keep track of size which is equal to the arrays length. The remove method uses a helper method entitled:
public int findSmallest(int parent)
where parent is the position in the array that the parent is stored at, and I am looking to return its smallest child. Order is simply the number of children each node that is not a leaf has. The code for my findSmallest:
public int findSmallest(int parent) {
int child = parent * order + 1;
int smallest = child;
for (int i = child; i < order + child; ++i) {
if (size >= i) {
return child;
}
if (queue[i].priority <= queue[smallest].priority) {
smallest = child;
}
}
return child;
}
It is currently an array out of bounds exception
Complete implementation of PriorityQueue Class I created:
import java.util.*;
public class PriorityQueue {
private class Item {
private int priority;
private Object data;
private Item(int p, Object d) {
priority = p;
data = d;
}
}
private Item queue[];
private int order;
private int size;
public PriorityQueue(int ord, int s) {
queue = new Item[s];
order = ord;
size = 0;
}
public int getPriority() {
if (size > 0) {
return queue[0].priority;
}
// -55 signifies that the queue is empty
return -55;
}
public Object getData() {
if (size > 0) {
return queue[0].priority;
}
return null;
}
public void remove() {
if (empty() == true) {
System.out.println("Queue is empty, there is nothing to remove.");
return;
}
Item x = queue[size - 1];
size--;
int child = 1;
int parent = 0;
while (child <= size) {
child = findSmallest(parent);
for (int i = order * parent + 1; i < child + order; i++) {
if (child < size && queue[i].priority < queue[child].priority)
child = i;
}
if (x.priority < queue[child].priority)
break;
else {
parent = child;
queue[(child - 1) / order] = queue[child];
child = order * child + 1;
}
}
queue[(child - 1) / order] = x;
}
public int findSmallest(int parent) {
int child = parent * order + 1;
int smallest = child;
for (int i = child; i < order + child; ++i) {
if (size >= i) {
return child;
}
if (queue[i].priority <= queue[smallest].priority) {
smallest = child;
}
}
return child;
}
public int getSize() {
return size;
}
public boolean full() {
return size == queue.length;
}
public boolean empty() {
if (size > 0) {
return false;
}
return true;
}
public void insert(int p, Object d) {
// 1. Create a new Item and add it to queue[size]
// Somewhere store new node created as TEMP
// 2. while loop
// 3. check if node has parent
// 4. if it does --> check if parent.priority > child.priority
// 5. if yes, swap
if (full() == true) {
System.out.println("Queue is full, cannot add new node.");
return;
}
queue[size] = new Item(p, d);
sort();
size++;
}
// Sort() swaps new child node with parents if child.priority < parent.priority
public void sort() {
int child = size;
Item temp = queue[child];
while ( child > 0 && queue[child].priority < queue[(child-1)/(order)].priority) {
queue[child] = queue[(child-1)/order];
queue[(child-1)/order] = temp;
child = ((child - 1) / order);
}
queue[child] = temp;
}
public static void main(String[] args) {
PriorityQueue p1 = new PriorityQueue(5, 100);
PriorityQueue p2 = new PriorityQueue(6, 100);
PriorityQueue p3 = new PriorityQueue(7, 100);
int p = -1; //pointless initialization to keep the compiler happy
p1.insert(0, new Integer(0));
System.out.println("First insert");
for (int i = 1; i < 100; i++)
p1.insert(i, new Integer(i));
for (int i = 0; i < 100; i++)
p2.insert(i, new Integer(i));
for (int i = 0; i < 100; i++)
p3.insert(i, new Integer(i));
System.out.println("First insert tests");
System.out.print(p1.getPriority()+",");
while (!p1.empty()) {
p = p1.getPriority();
Object d = p1.getData();
p1.remove();
}
System.out.println(p);
System.out.print(p2.getPriority()+",");
while (!p2.empty()) {
p = p2.getPriority();
Object d = p2.getData();
p2.remove();
}
System.out.println(p);
System.out.print(p3.getPriority()+",");
while (!p3.empty()) {
p = p3.getPriority();
Object d = p3.getData();
p3.remove();
}
System.out.println(p);
System.out.println("First Remove Test");
for (int i = 100; i > 0 ; i--)
p1.insert(i, new Integer(i));
for (int i = 100; i > 0 ; i--)
p2.insert(i, new Integer(i));
for (int i = 100; i > 0 ; i--)
p3.insert(i, new Integer(i));
System.out.println("Second insert tests");
System.out.print(p1.getPriority()+",");
while (!p1.empty()) {
p = p1.getPriority();
Object d = p1.getData();
p1.remove();
}
System.out.println(p);
System.out.print(p2.getPriority()+",");
while (!p2.empty()) {
p = p2.getPriority();
Object d = p2.getData();
p2.remove();
}
System.out.println(p);
System.out.print(p3.getPriority()+",");
while (!p3.empty()) {
p = p3.getPriority();
Object d = p3.getData();
p3.remove();
}
System.out.println(p);
System.out.println("Second Remove Test");
Random r1 = new Random(1000);
while (!p3.full()) {
p = r1.nextInt(200);
System.out.print(p+",");
p3.insert(p, new Integer(p));
}
System.out.println();
while (!p3.empty()) {
System.out.print(p3.getPriority()+",");
Object d = p3.getData();
p3.remove();
}
System.out.println();
System.out.println("Third Remove Test");
}
}
Main includes 3 different ways I am testing my code.
If your problem is just with the findSmallest method, here is the solution:
public int findSmallest( int parent ) {
int smallestChild = -1;
int firstChild = parent * order + 1;
int lastChild = parent * order + order;
int currentSmallestChild = firstChild;
for ( int i = firstChild + 1; i <= lastChild; i++ ) {
if ( i > size || queue[i] == null ) {
break;
}
if ( queue[currentSmallestChild].priority > queue[i].priority ) {
currentSmallestChild = i;
smallestChild = i;
}
}
return smallestChild;
}
It will return -1 if there is not a smallest child. This code can be improved, I let it this way because I think it is easier to understand. Let me know if it works.
I am trying to complete an assignment where I need to write a Java program to take a string from the command line, and implement it as a Binary Tree in a specific order, then get the depth of the binary tree.
For example: "((3(4))7((5)9))"
would be entered as a tree with 7 as the root, 3 and 9 as the children, and 4 as a right child of 3, and 5 as a left child of 9.
My code is below.. The problem I am having is that, because I am basing my checks off of finding a right bracket, I am unsure how to get the elements correctly when they are not directly preceding the brackets, such as the 3 in the above string. Any direction would be greatly appreciated..
class Node {
int value;
Node left, right;
}
class BST {
public Node root;
// Add Node to Tree
public void add(int n) {
if (root == null) {
root = new Node( );
root.value = n;
}
else {
Node marker = root;
while (true) {
if (n < marker.value) {
if (marker.left == null) {
marker.left = new Node( );
marker.left.value = n;
break;
} else {
marker = marker.left;
}
} else {
if (marker.right == null) {
marker.right = new Node( );
marker.right.value = n;
break;
} else {
marker = marker.right;
}
}
}
}
} // End ADD
//Find Height of Tree
public int height(Node t) {
if (t.left == null && t.right == null) return 0;
if (t.left == null) return 1 + height(t.right);
if (t.right == null) return 1 + height(t.left);
return 1 + Math.max(height(t.left), height(t.right));
} // End HEIGHT
// Check if string contains an integer
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
} // End ISINT
public int elementCount(String[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (isInt(a[i])) count++;
}
return count;
}
} // End BST Class
public class Depth {
public static void main(String[] args) {
String[] a = args[0].split(" ");
BST tree = new BST();
int[] bcount = new int[10];
int[] elements = new int[10];
int x = 0, bracketcount = 0;
// Display entered string
System.out.print("Entered Format: ");
for (int j=0; j < a.length; j++) {
System.out.print(a[j]);
}
for (int i=0; i < a.length; i++) {
char c = a[i].charAt(0);
switch (c)
{
case '(':
bracketcount++;
break;
case ')':
if (isInt(a[i-1])) {
bcount[x] = bracketcount--;
elements[x++] = Integer.parseInt(a[i-1]);
}
break;
case '1':
case '7':
default : // Illegal character
if ( (a[i-1].charAt(0) == ')') && (a[i+1].charAt(0) == '(') ) {
bcount[x] = bracketcount;
elements[x++] = Integer.parseInt(a[i]);
}
break;
}
}
System.out.println("\nTotal elements: " + tree.elementCount(a));
// Display BracketCounts
for (int w = 0; w < x; w++) {
System.out.print(bcount[w] + " ");
}
System.out.println(" ");
// Display Elements Array
for (int w = 0; w < x; w++) {
System.out.print(elements[w] + " ");
}
System.out.println("\nDepth: " + tree.height(tree.root));
// Build the tree
for (int y = 0; y < x-1; y++) {
for (int z = 1; z < tree.height(tree.root); z++) {
if (bcount[y] == z) {
tree.add(elements[y]);
}
}
}
} // End Main Function
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
}
} // End Depth Class
I would do a couple of statements to get access to a tree with that kind of shape:
For input string : input= "((3(4))7((5)9))"
You could do :
public class Trial {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "((3(4))7((5)9))";
String easier = input.replaceAll("\\(\\(", "");
String evenEasier = easier.replaceAll("\\)\\)", "");
System.out.println(evenEasier);
int firstVal = Integer.parseInt(evenEasier.substring(0, 1));
int firstBracketVal = Integer.parseInt(evenEasier.substring(2, 3));
int middleVal = Integer.parseInt(evenEasier.substring(3, 4));
int secondBracketVal = Integer.parseInt(evenEasier.substring(4,5));
int lastVal = Integer.parseInt(evenEasier.substring(6));
System.out.println("First Val:"+firstVal);
System.out.println("First bracket Val:"+firstBracketVal);
System.out.println("Middle Val:"+middleVal);
System.out.println("Second Bracket Val:"+secondBracketVal);
System.out.println("Last Val:"+lastVal);
}
}
This however would only ever work for entries in that specific format, if that were to change, or the length of the input goes up - this would work a bit or break.....If you need to be able to handle more complicated trees as input in this format a bit more thought would be needed on how to best handle and convert into your internal format for processing.
pseudocode:
function getNode(Node)
get one char;
if (the char is "(")
getNode(Node.left);
get one char;
end if;
Node.value = Integer(the char);
get one char;
if (the char is "(")
getNode(Node.right);
get one char;
end if;
//Now the char is ")" and useless.
end function
Before calling this function, you should get a "(" first.
In this method, the framwork of a Node in string is "[leftchild or NULL] value [rightchild or NULL])".
"("is not belong to the Node, but ")" is.
hey guys i have a problem when trying to print out the circular queue array
heres my code:
public class CircularQueue {
private int [] queue;
private int front, rear;
// do not change the constructor
CircularQueue() {
queue = new int [5];
front = 0;
rear = -1;
}
// FILL IN:
// throws DSException if out of space
public void enqueue ( int item ) throws DSException {
if ( front == 0 && rear == -1 ){
throw new DSException();
}
queue[rear+1] = item;
rear = (rear+1)%queue.length;
}
// FILL IN:
// throws DSException if no element in the queue
// return the dequeued value
public int dequeue () throws DSException {
if ( front == 0 && rear == -1 ){
throw new DSException();
}
int temp = queue[front];
queue[front] = 0;
front = (front+1)%queue.length;
return temp;
}
// FILL IN:
// return the value at beginning of the queue
// throws DSException if no element in the queue
public int first () throws DSException {
return front;
}
// FILL IN:
// print the circular queue in the following format
// - print "+" before the value at the front
// - print "-" after the value at the rear
// - print "." for the places without valid element.
public void print () {
System.out.print(" <");
for ( int i = 0; i < queue.length; i++ ){
if ( front == 0 && rear == -1 ){
System.out.print("."+"\t");
} else if ( i == front ) {
System.out.print("+"+ queue[i]);
} else if ( i == rear ) {
System.out.print( queue[i]+ "-");
} else if ( i == front && i == rear) {
System.out.print("+"+ queue[i] +"-");
} else {
System.out.print( queue[i] );
}
}
System.out.print(">\n");
}
}
and here's the result
EMPTY:
<. . . . . >
ENQUEUE (0):
i am supposed to enqueue 0-4 and dequeue some element but it stops after enqueue 0.
A CircularQueue can be in 3 states whose invariants are given below :
Empty : front == -1 && rear == -1
Full : (rear+1)%queue.length == front
Neither empty nor full : Does not satisfy the conditions mentioned above
public class CircularQueue {
private int [] queue;
private int front, rear;
// do not change the constructor
CircularQueue() {
queue = new int [5];
front = -1;
rear = -1;
}
// FILL IN:
// throws DSException if out of space
public void enqueue ( int item ) throws DSException,Exception {
if ( front == -1 && rear == -1 ){
front = 0;
rear = 0;
queue[rear] = item;
}
else if((rear+1)%queue.length == front) {
throw new Exception("Full");
}
else {
rear = (rear+1)%queue.length;
queue[rear] = item;
}
}
// FILL IN:
// throws DSException if no element in the queue
// return the dequeued value
public int dequeue () throws DSException {
if ( front == -1 && rear == -1 ){
throw new DSException();
}
else {
int ret = queue[front];
if(rear==front) {
rear = -1;
front = -1;
}
else {
front = (front+1)%queue.length;
}
return ret;
}
}
// FILL IN:
// return the value at beginning of the queue
// throws DSException if no element in the queue
public int first () throws DSException {
if(front==-1 && rear ==-1) {
throw new DSException();
}
return queue[front];
}
// FILL IN:
// print the circular queue in the following format
// - print "+" before the value at the front
// - print "-" after the value at the rear
// - print "." for the places without valid element.
public void print () {
if(front==-1 && rear == -1) {
for(int i=0;i<queue.length;i++) {
System.out.print(".");
}
}
else {
if(front<=rear) {
for(int i=0;i<=front-1;i++) {
System.out.print(".");
}
System.out.print("+");
for(int i=front;i<=rear;i++) {
System.out.print(queue[i]);
}
System.out.print("-");
for(int i=rear+1;i<=queue.length-1;i++) {
System.out.print(".");
}
}
else {
for(int i=0;i<=rear;i++) {
System.out.print(queue[i]);
}
System.out.print("-");
for(int i=rear+1;i<=front-1;i++) {
System.out.print(".");
}
System.out.print("+");
for(int i=front;i<=queue.length-1;i++) {
System.out.print(queue[i]);
}
}
}
}
}
This is my approach. But I am assuming here that the empty blocks in the array are initialized with zero, and that any valid entry would be non-zero. Also, it will print zeros in case the queue is partially filled.
public void print() {
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
System.out.println("In order from latest to oldest");
int i = front;
while (i < array.length) {
System.out.print(array[i] + " ");
i++;
}
i = i % array.length;
if(array[i] != 0) {
while(i < front) {
System.out.print(array[i] + " ");
i++;
}
}
}
}
Problem with circular arrays and front/rear indices is that 'full' and 'empty' are indistinguishable. You will have to add a boolean 'empty', which is initially true, and is used in the tests.
private int [] queue;
private int front, rear;
private boolean empty;
// do not change the constructor
CircularQueue() {
queue = new int [5];
front = 0;
rear = -1;
empty = true;
}
// FILL IN:
// throws DSException if out of space
public void enqueue ( int item ) throws DSException {
if (!empty && (front - rear + queue.length) % queue.length == 1){
throw new DSException();
}
queue[rear+1] = item;
rear = (rear+1)%queue.length;
empty = false;
}
// FILL IN:
// throws DSException if no element in the queue
// return the dequeued value
public int dequeue () throws DSException {
if (empty){
throw new DSException();
}
int temp = queue[front];
queue[front] = 0;
front = (front+1)%queue.length;
empty = (front - rear + queue.length) % queue.length == 1;
return temp;
}