displaying circular queue in java - java

I have the following code where I have implemented a circular array. The problem comes when I try to display it. The display method works well until the array gets full and last goes back to 0. Therefore last and first are both 0 and the for loop doesn't execute.
public class PassengerQueue
{
private Passenger[] queueArray = new Passenger[TrainStation.WAITING_ROOM_CAPACITY];
private int first = 0;
private int last = 0;
private int maxStayInQueue = 0; //number of seconds that the passenger who stayed longest in the queue
private int maxLength = 0; //the maximum legth that was reached by the queue
private int currentSize = 0;
public void add(Passenger next)
{
//if the queue is not full - check for the circular queue
if (isFull()){
System.out.println("The queue is full");
}
else
{
queueArray[last] = next;
last = (last + 1) % queueArray.length;
currentSize++;
maxLength++;
}
}
public Passenger remove()
{
Passenger removedPassenger = null;
//if the queue array is not empty
//remove passenger
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
removedPassenger = queueArray[first];
queueArray[first] = null;
first = (first + 1) % queueArray.length;
currentSize--;
}
return removedPassenger;
}
public Boolean isEmpty()
{
return (currentSize == 0);
}
public Boolean isFull()
{
return (currentSize == queueArray.length);
}
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = first; i < last; i++)
{
queueArray[i].display();
}
}
}
Any help would be appreciated! Thank You

You can change the loop so it iterates from 0 to size. This also fixes the problem where last is less than first because items have been removed.
for(int i = 0; i < currentSize; i++)
{
queueArray[(first + i) % queueArray.length].display();
}

Just use the properties on the array itself to display:
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = 0; i < queueArray.length; i++)
{
queueArray[i].display();
}
}
}

Related

How can I fix my code to give the correct output instead of giving nothing?

When i run my code, i get nothing as my output. I suspect my code stops on this method:
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
I think it stops at the above method because this code:
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
only returns -1. If i remove the return -1; then Java thinks that there is an error because there is no return statment. I tried adding an else, but i still get the same error.
This is the whole code:
/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);
/** Adds the given value to the beginning of the list */
void prepend(char value);
/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);
/** Returns the number of values currently in our list */
int size();
/** Retrieves the value at the given position */
char getValueAt(int position);
/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}
/** Array implementation of our List */
class ListAsArray implements IList {
// initialize array to a size of 30 elements
// this will prevent the need to resize our array
char[] theArray = new char[30];
public void append(char value)
{
//Count until you find a place in the array that is empty, then insert
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
theArray[i] = value;
}
}
}
public void prepend(char value)
{
//Count until you find a empty value
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
//Once you find the empty value move everything over
for(int j = theArray.length; j != 0; j--)
{
theArray[i] = theArray[i + 1];
}
}
}
//Finally you want to actually add in the number in the first position
theArray[0] = value;
}
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
public int size()
{
//Count until you find a place in the array that is empty, then return the number
int count = 0;
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
return count;
}
count ++;
}
return 0;
}
public char getValueAt(int position)
{
return theArray[position];
}
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
}
/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
//Point to first node and second node
private Node head;
private Node tail;
//Constructor sets head and tail to null
public void LinkedList()
{
head = null;
tail = null;
}
public void append(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
//Set new node to be after current end
tail.setNext(temp);
//Set as new tail
tail = temp;
}
}
public void prepend(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
temp.next = head;
head = temp;
}
}
public void deleteAt(int position)
{
//Make the head node the next node if its the first one
if(position == 0)
{
head=head.next;
}
//If that wasn't the case...
Node current = head;
for(int i = 0; i < position-1; i++)
{
current = current.next;
}
current.next = current.next.next;
if(current.getNext() == null)
{
tail = current;
}
}
public int size()
{
Node temp = head;
for (int i = 0; i != 103; i++)
{
if (temp == tail)
{
return i;
}
}
return 0;
}
public char getValueAt(int position)
{
Node temp=head;
for(int i=0; i < position; i++)
{
temp=temp.next;
}
return temp.data;
}
public int positionOf(char value)
{
//Start at the beginning
int position = 0;
Node current = head;
//Look until we find target data
while (current.getData() != value)
{
//Move to next node
current = current.getNext();
//Increment position
position++;
}
//return position found
return position;
}
}
/** A singly linked list node for our singly linked list */
class Node {
//The node data and link to next node
public char data;
public Node next;
//Constructor
public Node(char data)
{
this.data = data;
this.next = null;
}
//Accessor
public char getData()
{
return data;
}
//Accessor
public Node getNext()
{
return next;
}
//Mutator
public void setData(char data)
{
this.data = data;
}
//Mutator
public void setNext(Node next)
{
this.next = next;
}
}
This is main:
/** contains our entry point */
public class Main {
/** entry point - DO NOT CHANGE the pre-existing code below */
public static void main(String[] args) {
int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
int[] numbers2 = {97,59,111,53,33,111,106,42,50};
int[] numbers3 = {116,104,32,111,116,32,111,71};
/// List as an Array
IList array = new ListAsArray();
// add values
for(int num : numbers) {
array.append((char)num);
}
for(int num : numbers3) {
array.prepend((char)num);
}
// delete some values
int position;
position = array.positionOf((char)105);
array.deleteAt(position);
position = array.positionOf((char)65);
array.deleteAt(position);
position = array.positionOf((char)88);
array.deleteAt(position);
// print em
position = 0;
while (position < array.size()) {
System.out.print(array.getValueAt(position));
position++;
}
/// List as a Linked List
IList linkedList = new ListAsLinkedList();
// add values
for(int num : numbers2) {
linkedList.append((char)num);
}
linkedList.prepend((char)55);
linkedList.prepend((char)121);
// delete some values
position = linkedList.positionOf((char)59);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)33);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)42);
linkedList.deleteAt(position);
// print em
position = 0;
while (position < linkedList.size()) {
System.out.print(linkedList.getValueAt(position));
position++;
}
System.out.println();
// ???
}
}
It should be outputting a link pertaining to the next part of my assignment.
The size() method always returns 0 according to your input.
size() method as per your code doesn't give you the length of the array to iterate over. Therefore you should use array length i.e theArray.length in positionOf() method's for loop instead of size() method.

How to double the size of a queue in java

I've been trying to double the size of my queue and I have tried several different methods, this one has given me the closest result to what I am trying to get, however, it copies all the values already in the queue into the newly created spaces instead of leaving them empty for me to add more objects.
I have two classes, and the only part I need to change is the enqueue method.
The last line should print 50 40 30 20 60 70 instead.
public class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count ==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
} else
System.out.println("Queue is full. Doubling the size.");
count = (QUEUE_SIZE*2);
System.out.println("New max size is: " + QUEUE_SIZE);
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println("Trying to dequeue from empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println("Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
import java.util.Stack;
public class Runner {
public static void main(String[] args) {
Queue q = new Queue();
createQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to dequque one element.");
q.dequeue();
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to reverse my queue: ");
reverseQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 60.");
q.enqueue(60);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 70.");
q.enqueue(70);
System.out.println("My queue is as follows: ");
printQueue(q);
}
public static Queue createQueue(Queue q){
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
return q;
}
public static void printQueue(Queue q){
int s = q.size();
for(int i=0; i<s; i++){
int temp = (int)q.dequeue();
q.enqueue(temp);
System.out.print(temp+ " ");
}
System.out.println();
}
public static void reverseQueue(Queue q){
Stack s = new Stack();
while(!q.isEmpty()){
s.push(q.dequeue());
}while(!s.isEmpty()){
q.enqueue(s.pop());
}
}
}
The else block in enqueue(Object newItem) does not insert new Object so it should be like this :
public void enqueue(Object newItem) {
if (!isFull()) {
back = (back + 1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
}
else {
System.out.println("Queue is full. Doubling the size.");
QUEUE_SIZE = (QUEUE_SIZE * 2); // double queue size not count
System.out.println("New max size is: " + QUEUE_SIZE);
Object[] temp = new Object[QUEUE_SIZE]; // temp array
System.arraycopy(items, front, temp, front, items.length - front); // copy the elements from front index to items.length-front
if (front != 0) {
System.arraycopy(items, 0, temp, items.length, front); // copy the elements in the range items[0] to items[back] into the new array
}
items = temp; // set items to temp array
back = front + count;
items[back] = newItem; // set new item
count++; // increment count
}
}
It is about printQueue() method, after the count = (QUEUE_SIZE*2); line of enqueue() method the size of items array actually didn't expand. It is still 5 in any case, count = (QUEUE_SIZE*2); provide that isFull() method returns false.
If you debug printQueue() method, you will see that int s = 10 but items array still [30, 20, 60, 50, 40].
After Queue becomes full, You are not enqueuing the items. So the item is not inserted into the queue after becomes full.Have modified the code.
package org.sunil.addressbook.dao;
import java.util.Stack;
class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count ==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
// System.out.println("back output is "+back);
items[back] = newItem;
count++;
} else{
System.out.println("Queue is full. Doubling the size.");
back=QUEUE_SIZE-1;
QUEUE_SIZE = (QUEUE_SIZE*2);
Object[] temp = new Object[QUEUE_SIZE];
int j=0;
for (int i = front; i < items.length; i++){
temp[j] = items[i];
j++;
}
for (int i = 0; i < front; i++){
temp[j] = items[i];
j++;
}
items = temp;
front=0;
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
}
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println("Trying to dequeue from empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println("Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
public class Runner {
public static void main(String[] args) {
Queue q = new Queue();
createQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to dequque one element.");
q.dequeue();
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to reverse my queue: ");
reverseQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 60.");
q.enqueue(60);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 70.");
q.enqueue(70);
System.out.println("My queue is as follows: ");
printQueue(q);
}
public static Queue createQueue(Queue q){
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
return q;
}
public static void printQueue(Queue q){
int s = q.size();
for(int i=0; i<s; i++){
int temp = (Integer)q.dequeue();
q.enqueue(temp);
System.out.print(temp+ " ");
}
System.out.println();
}
public static void reverseQueue(Queue q){
Stack s = new Stack();
while(!q.isEmpty()){
s.push(q.dequeue());
}while(!s.isEmpty()){
q.enqueue(s.pop());
}
}
}

Modifying toString Circular Array Buffer

I have the java code and been able to come up with a toString as shown below in the code:
public class CircularArrayQueue<T> implements QueueADT<T>
{
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private T[] queue;
//-----------------------------------------------------------------
// Creates an empty queue using the default capacity.
//-----------------------------------------------------------------
public CircularArrayQueue()
{
front = rear = count = 0;
queue = (T[]) (new Object[DEFAULT_CAPACITY]);
}
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public CircularArrayQueue (int initialCapacity)
{
front = rear = count = 0;
queue = ( (T[])(new Object[initialCapacity]) );
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enqueue (T element)
{
if (size() == queue.length)
expandCapacity();
queue[rear] = element;
rear = (rear+1) % queue.length;
count++;
}
//-----------------------------------------------------------------
// Removes the element at the front of the queue and returns a
// reference to it. Throws an EmptyCollectionException if the
// queue is empty.
//-----------------------------------------------------------------
public T dequeue() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("queue");
T result = queue[front];
queue[front] = null;
front = (front+1) % queue.length;
count--;
return result;
}
//-----------------------------------------------------------------
// Returns a reference to the element at the front of the queue.
// The element is not removed from the queue. Throws an
// EmptyCollectionException if the queue is empty.
//-----------------------------------------------------------------
public T first() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("queue");
return queue[front];
}
//-----------------------------------------------------------------
// Returns true if this queue is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty()
{
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this queue.
//-----------------------------------------------------------------
public int size()
{
return count;
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
public String toString()
{
String result = "";
int scan = 0;
while(scan < count)
{
if(queue[scan]!=null)
{
result += queue[scan].toString()+"\n";
}
scan++;
}
return result;
}
//-----------------------------------------------------------------
// Creates a new array to store the contents of the queue with
// twice the capacity of the old one.
//-----------------------------------------------------------------
public void expandCapacity()
{
T[] larger = (T[])(new Object[queue.length *2]);
for(int scan=0; scan < count; scan++)
{
larger[scan] = queue[front];
front=(front+1) % queue.length;
}
front = 0;
rear = count;
queue = larger;
}
}
How can I modify my toString based on these output for my queue:
I want to Start with an initial String showing the number of cars
If the queue is empty, thenI will return the initial String.
If front is at, or ahead of, back
I want to add a line for each car from front to the end
then add lines for those from the start of the array to back-1
else I want to add a line for each car between front and back-1.
This is my current toString() :
public String toString()
{
String result = "";
for (int scan=0; scan < rear; scan++)
result = result + queue[scan].toString() + "\n";
return result;
}
You wrote the pseudo-code, a few if/else-if blocks do the rest.
public String toString()
{
String result = String.format("There are %d items in the queue.", count);
if (count == 0)
{
return result;
}
else if (front >= back)
{
for (int i = front; i < count; i++)
{
result += queue[i].toString() + "\n";
}
for (int i = 0; i < back; i++)
{
result += queue[i].toString() + "\n";
}
}
else
{
for (int i = front; i < back; i++)
{
result += queue[i].toString() + "\n";
}
}
return result;
}

Arrival time cannot be sorted correctly in Java

Greeting to everyone. I currently work on a program that sorting the emergency number of patients(the number that assigned by nurse when they enter the emergency room and this number determines the seriousness of their sickness too). However, if there are more than 1 patient who hold the same emergency numbers(eg: 2 patients hold emergency number 1), the one who came earlier should receive the treatment first. For this reason, I have 2 sortings, one is to sort the emergency number in ascending order and the other is to sort the time in ascending order too. But unfortunately the second sorting cannot work correctly.The following are the explanations for the type of emergency numbers:
Emergency number : 1 – Immediately life threatening
Emergency number : 2 – Urgent, but not immediately life threatening
Emergency number : 3 – Less urgent
So,now comes the coding part(Please note that this is a linkedlist)
Interface:
public interface ListInterface<T> {
public boolean add(T newEntry);
public boolean add(int newPosition, T newEntry);
public T remove(int givenPosition);
public void clear();
public boolean replace(int givenPosition, T newEntry);
public T getEntry(int givenPosition);
public boolean contains(T anEntry);
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
LList class:
/**
* LList.java
* A class that implements the ADT list by using a chain of nodes,
* with the node implemented as an inner class.
*/
public class LList<T> implements ListInterface<T> {
private Node firstNode; // reference to first node
private int length; // number of entries in list
public LList() {
clear();
}
public final void clear() {
firstNode = null;
length = 0;
}
public boolean add(T newEntry) {
Node newNode = new Node(newEntry); // create the new node
if (isEmpty()) // if empty list
firstNode = newNode;
else { // add to end of nonempty list
Node currentNode = firstNode; // traverse linked list with p pointing to the current node
while (currentNode.next != null) { // while have not reached the last node
currentNode = currentNode.next;
}
currentNode.next = newNode; // make last node reference new node
}
length++;
return true;
}
public boolean add(int newPosition, T newEntry) { // OutOfMemoryError possible
boolean isSuccessful = true;
if ((newPosition >= 1) && (newPosition <= length+1)) {
Node newNode = new Node(newEntry);
if (isEmpty() || (newPosition == 1)) { // case 1: add to beginning of list
newNode.next = firstNode;
firstNode = newNode;
}
else { // case 2: list is not empty and newPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < newPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
newNode.next = nodeBefore.next; // make new node point to current node at newPosition
nodeBefore.next = newNode; // make the node before point to the new node
}
length++;
}
else
isSuccessful = false;
return isSuccessful;
}
public T remove(int givenPosition) {
T result = null; // return value
if ((givenPosition >= 1) && (givenPosition <= length)) {
if (givenPosition == 1) { // case 1: remove first entry
result = firstNode.data; // save entry to be removed
firstNode = firstNode.next;
}
else { // case 2: givenPosition > 1
Node nodeBefore = firstNode;
for (int i = 1; i < givenPosition - 1; ++i) {
nodeBefore = nodeBefore.next; // advance nodeBefore to its next node
}
result = nodeBefore.next.data; // save entry to be removed
nodeBefore.next = nodeBefore.next.next; // make node before point to node after the
} // one to be deleted (to disconnect node from chain)
length--;
}
return result; // return removed entry, or
// null if operation fails
}
public boolean replace(int givenPosition, T newEntry) {
boolean isSuccessful = true;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
// System.out.println("Trace| currentNode.data = " + currentNode.data + "\t, i = " + i);
currentNode = currentNode.next; // advance currentNode to next node
}
currentNode.data = newEntry; // currentNode is pointing to the node at givenPosition
}
else
isSuccessful = false;
return isSuccessful;
}
public T getEntry(int givenPosition) {
T result = null;
if ((givenPosition >= 1) && (givenPosition <= length)) {
Node currentNode = firstNode;
for (int i = 0; i < givenPosition - 1; ++i) {
currentNode = currentNode.next; // advance currentNode to next node
}
result = currentNode.data; // currentNode is pointing to the node at givenPosition
}
return result;
}
public boolean contains(T anEntry) {
boolean found = false;
Node currentNode = firstNode;
while (!found && (currentNode != null)) {
if (anEntry.equals(currentNode.data))
found = true;
else
currentNode = currentNode.next;
}
return found;
}
public int getLength() {
return length;
}
public boolean isEmpty() {
boolean result;
if (length == 0)
result = true;
else
result = false;
return result;
}
public boolean isFull() {
return false;
}
public String toString() {
String outputStr = "";
Node currentNode = firstNode;
while (currentNode != null) {
outputStr += currentNode.data + "\n";
currentNode = currentNode.next;
}
return outputStr;
}
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
this.next = null;
}
private Node(T data, Node next) {
this.data = data;
this.next = next;
}
} // end Node
} // end LList
Patient class:
public class Patient {
private int emergencyNo;
private int queueTime;
private String patientName;
private String patientIC;
private String patientGender;
private String patientTelNo;
private String patientAdd;
private String visitDate;
public Patient() {
}
public Patient(int emergencyNo, int queueTime, String patientName, String patientIC, String patientGender, String patientTelNo, String patientAdd, String visitDate)
{
this.emergencyNo = emergencyNo;
this.queueTime = queueTime;
this.patientName = patientName;
this.patientIC = patientIC;
this.patientGender = patientGender;
this.patientTelNo = patientTelNo;
this.patientAdd = patientAdd;
this.visitDate = visitDate;
}
//set methods
public void setQueueTime(int queueTime)
{
this.queueTime = queueTime;
}
public boolean setEmergencyNo(int emergencyNo)
{
boolean varEmergencyNo = true;
if (emergencyNo != 1 && emergencyNo != 2 && emergencyNo != 3)
{
varEmergencyNo = false;
System.out.println("Emergency number is in invalid format!");
System.out.println("Emergency number is either 1, 2 or 3 only!");
System.out.println("\n");
}
else
{
this.emergencyNo = emergencyNo;
}
return varEmergencyNo;
}
public boolean setPatientName(String patientName)
{
boolean varPatientName = true;
if (patientName.equals("") || patientName.equals(null))
{
varPatientName = false;
System.out.println("The patient name cannot be empty!\n");
}
else
{
this.patientName = patientName;
}
return varPatientName;
}
public boolean setPatientIC(String patientIC)
{
boolean varPatientIC = true;
if(!patientIC.matches("^[0-9]{12}$"))
{
varPatientIC = false;
System.out.println("IC is in invalid format!");
System.out.println("It must consist of 12 numbers only!\n");
}
else
{
this.patientIC = patientIC;
}
return varPatientIC;
}
public boolean setPatientGender(String patientGender)
{
boolean varPatientGender = true;
if(!patientGender.equals("F") && !patientGender.equals("f") && !patientGender.equals("M") && !patientGender.equals("m"))
{
varPatientGender = false;
System.out.println("Gender is in invalid format!");
System.out.println("It must be either 'M' or 'F' only!\n");
}
else
{
this.patientGender = patientGender;
}
return varPatientGender;
}
public boolean setPatientTelNo(String patientTelNo)
{
boolean varPatientTelNo = true;
if((!patientTelNo.matches("^01[02346789]\\d{7}$")) && (!patientTelNo.matches("^03\\d{8}$")))
{
varPatientTelNo = false;
System.out.println("Invalid phone number!");
System.out.println("It must be in the following format : 0167890990 / 0342346789!\n");
System.out.print("\n");
}
else
{
this.patientTelNo = patientTelNo;
}
return varPatientTelNo;
}
public boolean setPatientAdd(String patientAdd)
{
boolean varPatientAdd = true;
if (patientAdd.equals("") || patientAdd.equals(null))
{
varPatientAdd = false;
System.out.println("The patient address cannot be empty!\n");
}
else
{
this.patientAdd = patientAdd;
}
return varPatientAdd;
}
public void setVisitDate(String visitDate)
{
this.visitDate = visitDate;
}
//get methods
public int getQueueTime()
{
return this.queueTime;
}
public int getEmergencyNo()
{
return this.emergencyNo;
}
public String getPatientName()
{
return this.patientName;
}
public String getPatientIC()
{
return this.patientIC;
}
public String getPatientGender()
{
return this.patientGender;
}
public String getPatientTelNo()
{
return this.patientTelNo;
}
public String getPatientAdd()
{
return this.patientAdd;
}
public String getVisitDate()
{
return this.visitDate;
}
#Override
public String toString()
{
return (this.emergencyNo + "\t\t" + this.patientName + "\t\t" + this.patientIC +
"\t\t" + this.patientGender + "\t\t" + this.patientTelNo + "\t\t" + this.patientAdd + "\t\t" + this.visitDate);
}
public String anotherToString()
{
return (this.emergencyNo + "\t\t\t\t\t\t" + this.patientName + "\t\t\t " + this.visitDate);
}
}
EmergencyCmp(Comparator)--->use for sorting the emergency numbers of the patients
import java.util.Comparator;
public class EmergencyCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
return 1;
}
else
{
return -1;
}
}
}
QueueCmp(Comparator)--->use for sorting the arrival time of the patients
import java.util.Comparator;
public class QueueCmp implements Comparator<Patient>
{
#Override
public int compare(Patient p1, Patient p2)
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
}
Main function:
import java.util.Calendar;
import java.util.Scanner;
import java.util.Arrays;
import java.util.*;
public class DSA {
public DSA() {
}
public static void main(String[] args) {
//patient's attributes
int emergencyNo;
int queueTime;
String patientName;
String patientIC;
String patientGender;
String patientTelNo;
String patientAdd;
String visitDate;
//counter
int j = 0;
int x = 0;
int y = 0;
int z = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int countEnteredPatient = 1;
int totalCount = 0;
//calendar
int nowYr, nowMn, nowDy, nowHr, nowMt, nowSc;
//others
boolean enterNewPatient = true;
String continueInput;
boolean enterNewPatient1 = true;
String continueInput1;
boolean continueEmergencyNo;
Scanner scan = new Scanner(System.in);
ListInterface<Patient> patientList = new LList<Patient>();
ListInterface<Patient> newPatientList = new LList<Patient>();
Patient[] patientArr1 = new Patient[10000];
Patient[] patientArr2 = new Patient[10000];
Patient[] patientArr3 = new Patient[10000];
Patient tempoPatient;
do{
//do-while loop for entering new patient details after viewing patient list
System.out.println("Welcome to Hospital Ten Stars!\n");
do{
//do-while loop for entering new patient details
System.out.println("Entering details of patient " + countEnteredPatient);
System.out.println("===================================\n");
Calendar calendar = Calendar.getInstance();
nowYr = calendar.get(Calendar.YEAR);
nowMn = calendar.get(Calendar.MONTH);
nowDy = calendar.get(Calendar.DAY_OF_MONTH);
nowHr = calendar.get(Calendar.HOUR);
nowMt = calendar.get(Calendar.MINUTE);
nowSc = calendar.get(Calendar.SECOND);
queueTime = calendar.get(Calendar.MILLISECOND);
visitDate = nowDy + "/" + nowMn + "/" + nowYr + ", " + nowHr + ":" + nowMt + ":" + nowSc;
//input emergency number
do{
tempoPatient = new Patient();
continueEmergencyNo = false;
int EmergencyNoOption;
try
{
do{
System.out.print("Please select 1 – Immediately life threatening, 2 – Urgent, but not immediately life threatening or 3 – Less urgent(Eg: 1) : ");
EmergencyNoOption = scan.nextInt();
scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setEmergencyNo(EmergencyNoOption) == false);
}
catch(InputMismatchException ex)
{
System.out.print("\n");
System.out.println("Invalid input detected.");
scan.nextLine();
System.out.print("\n");
continueEmergencyNo = true;
}
}while(continueEmergencyNo);
//input patient name
do{
System.out.print("Patient name(Eg: Christine Redfield) : ");
patientName = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientName(patientName) == false);
//input patient ic no
do{
System.out.print("Patient IC number(Eg: 931231124567) : ");
patientIC = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientIC(patientIC) == false);
//input patient gender
do{
System.out.print("Patient gender(Eg: M) : ");
patientGender = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientGender(patientGender) == false);
//input patient tel. no
do{
System.out.print("Patient tel.No(without'-')(Eg: 0162345678/0342980123) : ");
patientTelNo = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientTelNo(patientTelNo) == false);
//input patient address
do{
System.out.print("Patient address(Eg: 4-C9 Jln Besar 123, Taman Besar, 56000 Kuala Lumpur) : ");
patientAdd = scan.nextLine();
System.out.print("\n");
}while(tempoPatient.setPatientAdd(patientAdd) == false);
tempoPatient.setQueueTime(queueTime);
tempoPatient.setVisitDate(visitDate);
patientList.add(tempoPatient);
//decide whether want to enter a new patient or not
do{
System.out.print("Do you want to enter another new patient?(Eg: Y/N) : ");
continueInput = scan.nextLine();
if(continueInput.equals("Y") || continueInput.equals("y"))
{
enterNewPatient = true;
System.out.print("\n");
}
else if(continueInput.equals("N") || continueInput.equals("n"))
{
enterNewPatient = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput.equals("Y") && !continueInput.equals("y") && !continueInput.equals("N") && !continueInput.equals("n"));
countEnteredPatient++;
}while(enterNewPatient); //end do-while loop for entering new patient details
System.out.println("\nWaiting list of patient will be displayed soon.\n");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
System.out.println("Waiting list of patients");
System.out.println("========================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= patientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + patientList.getEntry(i).anotherToString());
}
do{
System.out.print("\nSo, now do you want to enter another new patient?(Eg: Y/N) : ");
continueInput1 = scan.nextLine();
if(continueInput1.equals("Y") || continueInput1.equals("y"))
{
enterNewPatient1 = true;
System.out.print("\n");
}
else if(continueInput1.equals("N") || continueInput1.equals("n"))
{
enterNewPatient1 = false;
}
else
{
System.out.println("\n");
System.out.println("Please enter Y/N only.\n");
}
}while(!continueInput1.equals("Y") && !continueInput1.equals("y") && !continueInput1.equals("N") && !continueInput1.equals("n"));
}while(enterNewPatient1);//end do-while loop for entering new patient details after viewing patient list
System.out.println("\nNow rearranging the list based on the seriouness and their arrival time.");
try{
Thread.sleep(1000);
}
catch (Exception e)
{
}
//create an unsorted array
Patient[] tempoPatientArr = new Patient[patientList.getLength()];
//copy the contents of patientList into tempoPatientArr
for(int i = 1; i <= patientList.getLength(); i++ )
{
tempoPatientArr[i-1] = patientList.getEntry(i);
}
//sort tempoPatientArr
Arrays.sort(tempoPatientArr, new EmergencyCmp());
//the above part until this comment line does not have problem
//check the emergency no and then categorise accordingly
for(int i = 0; i < tempoPatientArr.length; i++)
{
if(tempoPatientArr[i].getEmergencyNo() == 1)
{
patientArr1[x] = tempoPatientArr[i];
x++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 2)
{
patientArr2[y] = tempoPatientArr[i];
y++;
}
else if(tempoPatientArr[i].getEmergencyNo() == 3)
{
patientArr3[z] = tempoPatientArr[i];
z++;
}
}
//to check how many !null elements by using count for 3 sub-arrays
for(int i = 0; i < patientArr1.length; i++)
{
if(patientArr1[i] != null)
{
count1++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr2.length; i++)
{
if(patientArr2[i] != null)
{
count2++;
}
else
{
break;
}
}
for(int i = 0; i < patientArr3.length; i++)
{
if(patientArr3[i] != null)
{
count3++;
}
else
{
break;
}
}
//new array with elimination of null values
Patient[] newPatientArr1 = new Patient[count1];
Patient[] newPatientArr2 = new Patient[count2];
Patient[] newPatientArr3 = new Patient[count3];
//copy the contents of old sub arrays(the arrays with null values) into the new sub arrays(without null values)
for(int i = 0; i < newPatientArr1.length; i++)
{
newPatientArr1[i] = patientArr1[i];
}
for(int i = 0; i < newPatientArr2.length; i++)
{
newPatientArr2[i] = patientArr2[i];
}
for(int i = 0; i < newPatientArr3.length; i++)
{
newPatientArr3[i] = patientArr3[i];
}
totalCount = count1 + count2 + count3;
//array that used to combine all the sub-arrays
Patient[] newPatientArr = new Patient[totalCount];
//sort all sub new arrays
Arrays.sort(newPatientArr1, new QueueCmp());
Arrays.sort(newPatientArr2, new QueueCmp());
Arrays.sort(newPatientArr3, new QueueCmp());
//combine the contents of sub new arrays into the newPatientArr array
do{
for (int i = 0; i < count1; i++)
{
newPatientArr[j] = newPatientArr1[i];
j++;
}
for (int b = 0; b < count2; b++)
{
newPatientArr[j] = newPatientArr2[b];
j++;
}
for (int c = 0; c < count3; c++)
{
newPatientArr[j] = newPatientArr3[c];
j++;
}
}while(j < totalCount);
//relink the nodes
for(int i = 0; i < newPatientArr.length; i++)
{
newPatientList.add(newPatientArr[i]);
}
System.out.println("\nSorted waiting list of patients");
System.out.println("===============================\n");
System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
System.out.println("============================================================================");
for(int i = 1; i <= newPatientList.getLength(); i++)
{
System.out.println(i + "\t\t\t" + newPatientList.getEntry(i).anotherToString());
}
}
}
Interface and LList class definitely do not have problems. So everyone can skip the 2 parts.
For the main function, I have a comment like this:
//the above part until this comment line does not have problem
When you all see the comment, that means the previous code does not have problem and you all may skip it and below is an attachment of the result that I got earlier:
So, from the picture you all can see that the sorting of arrival time is not correct. I hope that I can know why does this problem occurs since I cannot figure it out by myself. Thanks to all of you first.
So, after taking the advice of #Scott Hunter, I have made the following modification to the EmergencyCmp:
#Override
public int compare(Patient p1, Patient p2)
{
int value = 0;
if(p1.getEmergencyNo() > p2.getEmergencyNo())
{
value = 1;
}
else if(p1.getEmergencyNo() < p2.getEmergencyNo())
{
value = -1;
}
else if(p1.getEmergencyNo() == p2.getEmergencyNo())
{
if(p1.getQueueTime() > p2.getQueueTime())
{
return 1;
}
else
{
return -1;
}
}
return value;
}
However, the time sorting still produce a wrong result.
As I understand it (which I may not; you provided a LOT of extraneous stuff), it looks like you are trying to perform 2 distinct sorts, one after the other, such that the second is undoing the work of the first. Instead, you should define a single Comparator which compares emergency numbers and, only if they are the same, compares arrival times.

How to code Queue in Java

I'm trying to make a Queue in java.
The problem is that I don't know how to remove(?) a value from the array, the index value which I dequeue.
This is my code.
front() method is the dequeue part. and I used iter_ to set the current index position.
but as you can see, it dequeue's the corret value though the value still remains inside the array:(
public class IntQueue {
private int[] items_;
private int top_;
private int capacity_;
private int iter_;
public IntQueue(int capacity)
{
if(capacity <=0) capacity = 10;
capacity_ = capacity;
top_=0;
count_ = 0;
iter_=0;
items_= new int[capacity_];
}
public void push_back(int value)
{
if(top_>= capacity_)
overflow();
items_[top_++]=value;
count_++;
}
public int front()
{
if(top_<=0)
return 0;
int temp=0;
temp=items_[iter_];
count_--;
iter_++;
return temp;
}
public IntQueue clone()
{
IntQueue result = new IntQueue(capacity_);
for(int i=0 ; i<top_; ++i)
{
result.push_back(items_[i]);
}
/*for(int i=0 ; i<top_ ; ++i)
{
result.items_[i] = items_[i];
}*/
return result;
}
public void log()
{
for(int i=0 ; i <top_; ++i)
{
System.out.print(items_[i]);
if(i<top_ -1)
System.out.print(", ");
}
System.out.println();
}
}
private void overflow()
{
int[] newItem = new int[capacity_*2];
for(int i=0 ; i <top_; ++i)
newItem[i] = items_[i];
items_=newItem;
capacity_ *=2;
}
public static void main(String args[])
{
IntQueue queue = new IntQueue(2);
System.out.println("queue push 3: "); queue.push_back(3);
System.out.println("queue push 2: "); queue.push_back(2);
System.out.println("queue push 1: "); queue.push_back(1);
System.out.print("queue log: "); queue.log();
System.out.println("front " + queue.front());
System.out.println("front " + queue.front());
System.out.print("queue log: "); queue.log();
System.out.println("queue push 12: "); queue.push_back(12);
System.out.println("queue push 11: "); queue.push_back(11);
System.out.println("queue push 21: "); queue.push_back(21);
System.out.println("queue push 31: "); queue.push_back(31);
System.out.print("queue log: "); queue.log();
System.out.println("front " + queue.front());
System.out.println("front " + queue.front());
System.out.print("clone queue log: "); queue.clone().log();
}
}
What I don't get about your implementation is the following:
in the front method you're using iter_, but nowhere else. What is it good for?
if you're not using some kind of variable to keep track of what was removed without actually removing it, technically you'd need to shift all the items of the array to the left by one position, such that the first item is gone. This however is an O(N) operation.
It's easier to implement a queue using a linked list instead of an array.
When building a queue using an array, you can make a cyclic "pointer" to the head of the array, that you can use to retrieve the top.
Popping from the array is simply done by increasing this cyclic pointer.
Maintain an int variable: top, and once you need to pop an element do top = (top + 1) % items_.length
Retrieving the head is simple using items_[top].
Make sure you are guarding against popping elements that are not there (popping from an empty array).
You will probably also need to maintan a size variable for the queue's size.
Below I share my proposed solution for a simple thread-safe FIFO queue :D
public class Queue extends Object {
private int numElements;
private Node first;
private Node last;
/**
* Helper linked list class
*/
private static class Node {
private Object item;
private Node next;
}
/**
* Creates a new Queue object.
*/
public Queue() {
numElements = 0;
first = last = null;
}
/**
* Puts an object at the end of the queue.
*
* #param object
*/
public void putObject(Object object) {
synchronized (this) {
Node newNode = new Node();
newNode.item = object;
newNode.next = null;
if ( numElements == 0 ) {
first = last = newNode;
} else {
last.next = newNode;
last = newNode;
}
numElements += 1;
}
}
/**
* Gets an object from the beginning of the queue. The object is removed
* from the queue. If there are no objects in the queue, returns null.
*/
public Object getObject() {
synchronized (this) {
Object item = null;
if ( numElements > 0 ) {
item = first.item;
first = first.next;
numElements -= 1;
if (numElements == 0) {
last = null;
}
}
return item;
}
}
}
You cant remove an element from an array like a List. You need to move the values up and set the last index of the array as null. Take a look at the source of a java class that implement Queue.remove() method. For example following is the code from removeAt(int index) method of ArrayBlockingQueue.
void removeAt(int i) {
final E[] items = this.items;
// if removing front item, just advance
if (i == takeIndex) {
items[takeIndex] = null;
takeIndex = inc(takeIndex);
} else {
// slide over all others up through putIndex.
for (;;) {
int nexti = inc(i);
if (nexti != putIndex) {
items[i] = items[nexti];
i = nexti;
} else {
items[i] = null;
putIndex = i;
break;
}
}
}
--count;
notFull.signal();
}
when you design a queue, you need to decide the priority like how you are going to add and remove element from it.You can go through this link and implement it similar to this.
FIFO
A typical example is :
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> qe=new LinkedList<String>();
qe.add("b");
qe.add("a");
qe.add("c");
qe.add("e");
qe.add("d");
Iterator it=qe.iterator();
System.out.println("Initial Size of Queue :"+qe.size());
while(it.hasNext())
{
String iteratorValue=(String)it.next();
System.out.println("Queue Next Value :"+iteratorValue);
}
// get value and does not remove element from queue
System.out.println("Queue peek :"+qe.peek());
// get first value and remove that object from queue
System.out.println("Queue poll :"+qe.poll());
System.out.println("Final Size of Queue :"+qe.size());
}
}
First of all, you can't delete an item from an array, you can just overwrite it. You can use a List instead.
Another option is to use a circular queue, as amit's answer pointed out.
A simple solution using array is:
int queue[SIZE];
int first = 0;
int last = 0;
void enque(int i) {
if(last == SIZE)
throw new RuntimeExeption("Queue is full");
queue[last++] = i;
}
int deque() {
if(first == last)
throw new RuntimeExeption("Queue is empty");
return queue[first++];
}
Check this: it has enqueue and dequeue methods:
import java.io.*;
import java.lang.*;
class clrqueue
{
DataInputStream get=new DataInputStream(System.in);
int a[];
int i,front=0,rear=0,n,item,count=0;
void getdata()
{
try
{
System.out.println("Enter the limit");
n=Integer.parseInt(get.readLine());
a=new int[n];
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void enqueue()
{
try
{
if(count<n)
{
System.out.println("Enter the element to be added:");
item=Integer.parseInt(get.readLine());
a[rear]=item;
rear++;
count++;
}
else
System.out.println("QUEUE IS FULL");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void dequeue()
{
if(count!=0)
{
System.out.println("The item deleted is:"+a[front]);
front++;
count--;
}
else
System.out.println("QUEUE IS EMPTY");
if(rear==n)
rear=0;
}
void display()
{
int m=0;
if(count==0)
System.out.println("QUEUE IS EMPTY");
else
{
for(i=front;m<count;i++,m++)
System.out.println(" "+a[i]);
}
}
}
class Myqueue
{
public static void main(String arg[])
{
DataInputStream get=new DataInputStream(System.in);
int ch;
clrqueue obj=new clrqueue();
obj.getdata();
try
{
do
{
System.out.println(" 1.Enqueue 2.Dequeue 3.Display 4.Exit");
System.out.println("Enter the choice");
ch=Integer.parseInt(get.readLine());
switch (ch)
{
case 1:
obj.enqueue();
break;
case 2:
obj.dequeue();
break;
case 3:
obj.display();
break;
}
}
while(ch!=4);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
This is the code i implemented and is working fine in my system.
import java.util.Arrays;
public class Queue {
public int[] queue = new int[3];
int head = -1, tail =-1;
public void enqueue(int N){
if(tail == (queue.length-1))
queue = Arrays.copyOf(queue,2*queue.length);
if(head == -1){
head++;
tail++;
queue[head] = N;
}
else {
tail++;
queue[tail] = N;
}
}
public int dequeue(){
if(head == -1)
throw new IllegalStateException("Cannot dequeue if queue is empty");
int firstItem = queue[head];
if (head == tail) {
head = -1;
tail = -1;
}
else
head++;
return firstItem;
}
public void display(){
for (int i = head; i<= tail ; i++){
System.out.println("Display: " + queue[i]);
}
}
}
public class Main {
public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.display();
int dequeue = queue.dequeue();
System.out.println(dequeue);
queue.display();
int dequeue1 = queue.dequeue();
System.out.println(dequeue1);
queue.display();
}
}

Categories