Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need help on java Programming. Can Anyone tell me where I did wrong????
My Queue class is working like a Stack, not a Queue. If I enqueue 1, 2, and 3 (in that order) and then dequeue, it removes the 3, not the 1.
Thank you in advance!
This a Circular Array, and here my code:
import java.util.NoSuchElementException;
public class Queue implements QueueADT
{
private int front = 0;
private int back = 0;
private int [] a;
private int size = 10;
public Queue(){
a = new int [10];
}
public Queue(int size){
a = new int [size];
this.size = size;
}
//enqueue - adds an element to the back of the queue
public void enqueue(int element){
if(((back+1) - front) == -1 || ((back+1) - front) == (a.length - 1))
resizeArray();
if (back == a.length - 1)
back = 0;
a[back++] = element;
}
//dequeue - removes and returns the element from the
//front of the queue
public int dequeue(){
if(isEmpty())
throw new NoSuchElementException("Dequeue: Queue is empty");
if (front < back){
front ++;
return a[front-1];
}
else if (front > back){
front--;
return a[front++];
}
return 1;
}
//peek - returns but does not remove the element from
//the front of the queue
public int peek(){
if(isEmpty())
throw new NoSuchElementException("Peek: Queue is empty");
return a[front];
}
//isEmpty - determines if the queue is empty or not
public boolean isEmpty(){
return size() == 0;
}
private void resizeArray()
{
//double the size of the array
int[] newA = new int[a.length * 2];
int x = 0;
while(x < size - 1){
newA[x] = dequeue();
x++;
}
size = size *2;
front = 0;
back = x;
a = newA;
}
//size - returns the number of elements in our Queue
public int size(){
if (front > back ){
return size - (front - (back + 1));}
return back - front + 1;}
//toString - returns a String representation of our Queue
public String toString(){
if(isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
{
String s = "[ ";
//print queue
for(int i = 0; i < size(); i++)
s += a[i] + " ";
//print array
for(int j = size(); j < a.length; j++)
s += "* ";
s += "]";
return s;
}
}
//equals - determines if two queues are equivalent
//i.e. do they have the same elements in the same sequence
//ignoring the structure they are stored in
public boolean equals(Object otherQ){
if(otherQ == null)
return false;
else
{
//Figure out how many interfaces the other guy
//implements
int numIs = otherQ.getClass().getInterfaces().length;
boolean flag = false;
//look at all of the other guys interfaces
//and if he doesn't implement QueueADT, then
//he clearly isn't a Queue and we return false
for(int i = 0; i < numIs; i++)
{
if(this.getClass().getInterfaces()[0] ==
otherQ.getClass().getInterfaces()[i])
{
flag = true;
}
}
if(!flag)
return false;
else //we know that the other guy exists and
//we know that he implements QueueADT
{
QueueADT q = (QueueADT)otherQ;
if(this.size() != q.size())
return false;
else
{
boolean queuesEqual = true;
for(int i = 0; i < this.size(); i++)
{
int ourElement = this.dequeue();
int qElement = q.dequeue();
if(ourElement != qElement)
queuesEqual = false;
this.enqueue(ourElement);
q.enqueue(qElement);
}
//return our final answer
return queuesEqual;
}
}
}
}
public void showInnerWorkings(){
System.out.print("[");
for (int i = 0; i < this.a.length; i++)
System.out.print(this.a[i] +
(i != this.a.length - 1 ? ", " : ""));
System.out.println("]");
}
}
Your queue does not behave like a stack. It behaves like a buggy queue.
public static void main(String[] args) {
Queue q = new Queue();
q.enqueue(7);
q.enqueue(8);
q.enqueue(9);
System.out.println(q.dequeue()); // 7 (ok)
System.out.println(q.dequeue()); // 8 (ok)
System.out.println(q.dequeue()); // 9 (ok)
System.out.println(q.dequeue()); // 1 (bug)
System.out.println(q.dequeue()); // 1 (bug)
System.out.println(q.dequeue()); // 1 (bug)
}
Where is your code that made you conclude it was removing the 3 on the first call to dequeue?
Your Queue is seriously buggy.
Here is a start of a Unit Test which tests your Queue and shows some of the bugs.
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class QueueTest {
final Queue queue = new Queue();
#Test
public void givenNewQueue_thenSizeIsZero() {
assertEquals(0, queue.size());
}
#Test
public void givenNewQueue_thenIsEmpty() {
assertTrue(queue.isEmpty());
}
#Test(expected = NoSuchElementException.class)
public void givenNewQueue_whenDequeing_thenThrowsException() {
queue.dequeue();
}
#Test
public void givenNewQueue_whenQueueingElement_thenIsNotEmpty() {
queue.enqueue(0xA113);
assertFalse(queue.isEmpty());
}
#Test
public void givenNewQueue_whenQueueingElement_thenSizeIsOne() {
queue.enqueue(0xA113);
assertEquals(1, queue.size());
}
#Test
public void givenNewQueue_whenQueueingElement_thenReturnsElement() {
queue.enqueue(0xA113);
assertEquals(0xA113, queue.dequeue());
}
}
Related
import java.util.Scanner;
class ed {
int fr, r;
int q[];
int n;
ed(int x) {
n = x;
fr = -1;
r = -1;
q = new int[n];
}
void enque(int n) {
int val = n;
while (r < n-1) {
if (r==n-1) {
System.out.println("Overflow");
break;
}
else if (fr==-1 && r==-1) {
fr=0;
r=0;
q[r] = val;
}
else {
r += 1;
q[r] = val;
}
}
}
void deque() {
if (fr==-1 && r==-1) {
System.out.println("Underflow");
}
else if (fr==r) {
fr=-1;
r=-1;
}
else {
fr += 1;
}
}
void reverse(int[] q) {
int a = q[0];
deque();
reverse(q);
enque(a);
}
void printq() {
for (int i = fr; i<=r; i++) {
System.out.print(q[i] + " ");
}
}
}
public class q1 {
static Scanner f = new Scanner (System.in);
public static void main(String[] args) {
int n = f.nextInt();
ed que = new ed(n);
for (int i=0; i<n; i++) {
int x = f.nextInt();
que.enque(x);
}
// que.deque();
// que.printq();
que.reverse(que.q);
}
}
My aim is to reverse a queue (Array) using a recursive function, but in VS Code, the loop is running infinite times and I'm not getting a chance to see the error. I'd like to know my mistake, and any improvement is highly appreciated.
The class ed contains a constructor which initializes the array and the front, rear values. Enque method adds an element to the queue at the rear, deque method removes the front element. Reverse method takes an array input (queue), stores the foremost element in the variable a, deques it, calls itself, then enques it at the back. VS Code is showing the error at line 48 (reverse(q), when it calls itself) but it's not showing the error as it's so far up.
A lot of things are not going the right way in your queue implementation using arrays.
Like, in enque function, you can fill values from rear = 0 to rear = n - 1, because you have n positions available in the q array.
Your code was too long, unstructured, and a bit messy with no proper variable names, So, I didn't read it any further.
But one thing I can make out is that you need to read how to implement a queue using the array.
Now, coming to queue reversal using the recursion part.
Your approach was correct, you just missed out the base case condition.
Steps for reversing queue:
Your queue has some elements, we get the first element out of the queue.
Then, we assume I have a recursive function that reverses the rest of the queue.
In this reversed queue, I just have to push that first element to the back.
And coming to the base case, each time queue size is decreasing by 1, so at the end, the queue will become empty then we don't have to do anything, just return. THUS STOPPING THE RECURSION (which you missed).
Here, is my implementation if you need some reference:
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class Queue {
private int front, rear, capacity;
private int queue[];
Queue(int c) {
front = rear = 0;
capacity = c;
queue = new int[capacity];
}
int size() {
return rear - front;
}
void enqueue(int data) {
if (capacity == rear) {
System.out.printf("Queue is full.\n");
return;
}
else {
queue[rear] = data;
rear++;
}
}
void dequeue() {
if (front == rear) {
System.out.printf("Queue is empty.\n");
return;
}
else {
for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}
if (rear < capacity)
queue[rear] = 0;
rear--;
}
}
int front() {
if (front == rear) {
System.out.printf("\nQueue is Empty.\n");
return -1;
}
return queue[front];
}
void print() {
int i;
if (front == rear) {
System.out.printf("Queue is Empty.\n");
return;
}
for (i = front; i < rear; i++) {
System.out.printf(" %d, ", queue[i]);
}
System.out.println("");
return;
}
}
class GFG {
static Scanner scanner = new Scanner(System.in);
public static void reverseQueue(Queue queue) {
if (queue.size() == 0) {
return;
}
int frontElement = queue.front();
queue.dequeue();
reverseQueue(queue);
queue.enqueue(frontElement);
}
public static void main (String[] args) {
int queueSize = scanner.nextInt();
Queue queue = new Queue(queueSize);
for (int i = 0; i < queueSize; i++) {
int element = scanner.nextInt();
queue.enqueue(element);
}
queue.print();
reverseQueue(queue);
queue.print();
}
}
You can comment if anything is wrong, or need more clarification.
I am trying to implement a CircularArrayQueue. I've been given a JUnit test which my queue must pass.I suppose I am doing something wrong with the front and rear pointers. How should i approach learning data structures and algorithms ?
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue {
private Integer[] array;
// initial size of the array
private int N;
private int front;
private int rear;
public CircularArrayQueue() {
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size) {
this.N = size;
array = new Integer[N];
front = rear = 0;
}
// enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in) {
if (rear == N) {
if (front == 0) {
resize();
array[rear] = in;
rear++;
} else {
array[rear] = in;
rear = 0;
}
} else {
array[rear] = in;
rear++;
}
}
public void resize() {
Integer[] temp = new Integer[array.length * 2];
for (int i = 0; i < array.length; i++) {
temp[i] = array[i];
}
temp = array;
}
// dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The queue is full");
}
int headElement = array[front];
if (front == N) {
array[front] = null;
front = 0;
} else {
array[front] = null;
front++;
}
return headElement;
}
#Override
public int noItems() {
return N - getCapacityLeft();
}
#Override
public boolean isEmpty() {
return (getCapacityLeft() == N);
}
// return the number of indexes that are empty
public int getCapacityLeft() {
return (N - rear + front) % N;
}
}
Your initialization is absolutely fine, and we do start with:
front = rear = 0;
Befor adding an item to the Q, we modify rear as
rear = (rear + 1) % N;
The % allows us to maintain the circular property of the queue. Also you must be wondering that if we modify rear before adding any item, then 0 index is left empty, well we have to compromise here with one array item being left blank, in order to have correct implementations for checking of isEmpty() and isFull() functions:
That said, the correct code for isEmpty() is:
#Override
public boolean isEmpty()
{
return front == rear;
}
You should also have a function isFull() like:
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
Also the line temp = array; in your resize() should be array = temp; and you must also update the value of N after calling resize().
Hence, the correct code is:
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue
{
private Integer[] array;
//initial size of the array
private int N;
private int front;
private int rear;
private int count = 0;//total number of items currently in queue.
public CircularArrayQueue()
{
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size)
{
this.N = size;
array = new Integer[N];
front = rear = 0;
}
//enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in)
{
count++;
if (isFull())
{
resize();
rear = (rear + 1) % N;
array[rear] = in;
}
else
{
rear = (rear + 1) % N;
array[rear] = in;
}
}
public void resize()
{
Integer[] temp = new Integer[array.length*2];
N = array.length*2;
for(int i=0; i<array.length; i++)
{
temp[i] = array[i];
}
array = temp;
}
//dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException
{
if(isEmpty())
{
throw new Exception("The queue is empty");
}
front = (front + 1) % N;
int headElement = array[front];
count--;
return headElement;
}
#Override
public int noItems()
{
return count;
}
#Override
public boolean isEmpty()
{
return front == rear;
}
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
//return the number of indexes that are empty
public int getCapacityLeft()
{
return N - 1 - count;
}
}
I have a method which I basically want to simulate first filling the queue and then after that removing the first person and adding a new person each time in my public void mySimulation() method:
import java.util.*;
public class People {
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private ArrayList<thePeople> people;
private int theMaxCapacity;
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public People(int initialCapacity) {
front = rear = count = 0;
people = new ArrayList<thePeople>(Collections.nCopies(5, (thePeople) null));
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enque(thePeople element) {
if (this.isFull()) {
System.out.println("Queue Full");
System.exit(1);
} else {
people.set(rear, element);
rear = rear + 1;
if (rear == people.size()) {
rear = 0;
}
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 thePeople dequeue() {
if (isEmpty()) {
System.out.println("Empty Queue");
}
thePeople result = people.get(front);
people.set(front, null);
front = (front + 1) % people.size();
count--;
return result;
}
//-----------------------------------------------------------------
// 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;
}
public boolean isFull() {
return count == people.size();
}
public void mySimulation() {
Random rand1 = new Random();
thePeople theM = null;
if (this.isFull()) {
this.people.remove(0);
System.out.println("Enqueueing...");
this.enque(people.get(rand1.nextInt(people.size())));
thePeople r1 = people.get(rear - 1);
System.out.println(people.toString());
System.out.println(r1);
for (int e = 0; e < people.size(); e++) {
if (people.get(e) instanceof thePeople) {
System.out.println("G");
} else {
System.out.println("D");
}
}
}
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
#Override
public String toString() {
String result = "";
int scan = 0;
while (scan < count) {
if (people.get(scan) != null) {
result += people.get(scan).toString() + "\n";
}
scan++;
}
return result;
}
public static void main(String[] args) {
People Q1 = new People(25);
thePeople call1 = new thePeople("John King", "001 456 789");
thePeople call2 = new thePeople("Michael Fish", "789 654 321");
Q1.enque(call1);
Q1.enque(call2);
System.out.println(Q1.toString());
ArrayList<thePeople> callerDetails = new ArrayList<>(Arrays.asList(call1, call2));
Random rand = new Random();
for (int z = 0; z <= 4; z++) {
Q1.enque(callerDetails.get(rand.nextInt(callerDetails.size())));
}
System.out.println(Q1.toString());
}
}
any suggestions on how I could repeat this process such that I will first check that the queue is full,
if so remove the first item and add a new person to it using my arrayList each time i my my public void mySimulation() method: as I cant get my head round this at the moment?
Your code is filled with errors:
First make sure you remove the "the" you accidently placed before people in many lines of your code .
Then adjust some of your methods to the right parameters and return types.
As for you question:
it is simple
public void MySimulation(){
if(Queue.isFull()){
Queue.dequeue;}
Queue.enqueue;}
This is my Queue class. I have implemented it using arrays.
public class QueueUsingArray {
private int data[];
private int firstElementIndex;
private int nextElementIndex;
private int size;
public QueueUsingArray() {
data = new int[10];
firstElementIndex = -1;
nextElementIndex = 0;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
private void checkEmpty() throws QueueEmptyException {
if (size == 0) {
QueueEmptyException e = new QueueEmptyException();
throw e;
}
}
public int front() throws QueueEmptyException {
checkEmpty();
return data[firstElementIndex];
}
public int dequeue() throws QueueEmptyException {
checkEmpty();
int output = data[firstElementIndex];
size--;
data[firstElementIndex] = 0;
firstElementIndex = (firstElementIndex + 1) % data.length;
if (size == 0) {
firstElementIndex = -1;
nextElementIndex = 0;
size = 0;
}
return output;
}
public void enqueue(int element) {
if (size == data.length) {
int[] temp = data;
data = new int[data.length * 2];
int k = 0;
for (int i = firstElementIndex; i < temp.length; i++) {
data[k] = temp[i];
k++;
}
for (int i = 0; i < firstElementIndex; i++) {
data[k] = temp[i];
k++;
}
firstElementIndex = 0;
nextElementIndex = temp.length;
}
if (size == 0) {
firstElementIndex = 0;
}
data[nextElementIndex] = element;
size++;
nextElementIndex = (nextElementIndex + 1) % data.length;
}
}
Here is my QueueUse class.
public class QueueUse {
public static void main(String[] args) throws QueueEmptyException {
QueueUsingArray q=new QueueUsingArray();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
q.enqueue(70);
q.enqueue(80);
q.enqueue(90);
q.enqueue(100);
q.enqueue(110);
q.enqueue(120);
q.enqueue(130);
q.enqueue(140);
q.enqueue(150);
q.enqueue(160);
q.enqueue(170);
q.enqueue(180);
q.enqueue(190);
q.enqueue(200);
q.enqueue(210);
q.enqueue(220);
q.enqueue(230);
q.enqueue(240);
q.enqueue(250);
q.enqueue(260);
q.enqueue(270);
q.enqueue(280);
q.enqueue(290);
q.enqueue(300);
System.out.println("All elements");
for(int i=0;i<q.size();i++){
try {
System.out.println(q.dequeue());
} catch (QueueEmptyException e) {
System.out.println("Sorry");
}
}
}
}
My output is not complete. Output is not showing all the elements in my queue. What is the error. Output is only showing until 140 and not beyond that.
Your print method does not work because you decrement the size every time you invoke your dequeue() method in the for loop. If you are going to use a for loop you should be using a fixed size. Basically in this statement ( i < q.size() ) as i grows size decreases. If i = 0 and size = 4 the first loop i would be 1 and size would be 3. Your never going to get to the 0th or 1st element in your queue because by the next loop your already at i = 2 and size = 3.
first you should add a getter for the queue items
public int getElementAt(int index){
return data[index];
}
then you can call the method in the for loop for every index in data
int length = q.size();
for(int i = 0; i < length; i++){
System.out.println(q.getElementAt(i));
}
If it is not mandatory to do an array implementation, I would suggest using the Vector class because it has a better API for a queue. I would also suggest slowly tracing your program every time you have issues and to start with smaller test data sets to make tracing a easier.
public class Queue {
private Vector<String> data ;
Queue(){
data = new Vector();
}
public void enqueue(String item){
data.add(item);
}
public void dequeue(){
data.remove(0);
}
public void printQueueItems(){
int length = data.size();
for(int i = 0; i < length; i++){
System.out.println(data.get(i));
}
}
public static void main(String[] args) {
Queue myQ = new Queue();
myQ.enqueue("hello");
myQ.enqueue("world");
myQ.enqueue("!");
myQ.printQueueItems();
}
}
I was required to create a simple queue array implementation with basic methods as enqueue, dequeue, isEmpty, and stuff like that. My only problem is that Im stuck when it comes to the resize method, because if I want to add more values to my queue (with fixed size because is an array) I do not know how to make it work and keep all the values in place.
Everything works just in case you were wondering, the only thing is that doesnt work is my resize (the method wrote in here wasn't the only one I tried).
I'm going to put my main method as well if you want to try it, hope you can help, thanks.
Main Method:
public class MainQueue {
public static void main(String[] args) {
int capacity=10;
Queue<Integer> queue = new Queue<Integer>(capacity);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6);
queue.enqueue(7);
queue.enqueue(8);
queue.enqueue(9);
queue.enqueue(10);
System.out.println("Queue: "+ queue);
//WORKS SO FAR
queue.enqueue(11);
//11 is placed at the beginning of the queue
//instead at the end and my last value is null (?)
Class queue:
import java.util.NoSuchElementException;
public class Queue <E>{
private E[] elements;//array in generic
private int front;//first element or front of the queue
private int back;//last element or back of the queue
private int capacity; //capacity of the queue
private int count; //indicates number of elements currently stored in the queue
#SuppressWarnings("unchecked")
public Queue(int size)
{
capacity = size;
count = 0;
back = size-1;
front = 0;
elements =(E []) new Object[size]; //array empty
}
//Returns true if the queue is empty or false
public boolean isEmpty()
{
return count==0;//means its true
}
//Add elements to the queue
public void enqueue(E item)
{
if(count == capacity)
{
resize(capacity*2);
// System.out.println("Queue is full");
}
back =(back+1) % capacity; //example back=(0+1)%10=1
elements[back]=item;
//elements[0]=0
//item=elements[count];
count++;
}
//Public resize
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
}
//Dequeue method to remove head
public E dequeue()
{
if(isEmpty())
throw new NoSuchElementException("Dequeue: Queue is empty");
else
{
count--;
for(int x = 1; x <= count; x++)
{
elements[x-1] = elements[x];
}
capacity--;
return (E) elements;
}
}
//peek the first element
public E peek()
{
if(isEmpty())
{
throw new NoSuchElementException("Peek: Queue is empty");
}
else
return elements[front];
}
//Print queue as string
public String toString()
{
if(isEmpty()) {
System.out.println("Queue is empty.");
//throw new NoSuchElementException("Queue is empty");
}
String s = "[";
for(int i = 0; i <count; i++)
{
if(i != 0)
s += ", ";
s = s + elements[i];// [value1,value2,....]
}
s +="]";
return s;
}
public void delete() { //Delete everything
count = 0;
}
}
you forgot to update stuff when resizing:
front, capacity and back .
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
front = 0;
back = count-1;
capacity=reSize;
}
You have few mistakes in resizing when enqueing item which expand queue.
in resize algorithm
current = (current + 1) % count; should be (current + 1) % capacity
You have to change capacity value in resize function
capacity = resize;
Why are you changing capacity when dequeing?