Below is my queue code. Whenever I enter nos. 1 to 8, it will print 1-7 then replace 8 with 0. If there are any other mistakes in my code please let me know.

import java.util.Arrays; 
import java.util.Scanner; 

public class Queue { 

private int[] elements; //integer values from scanner 
private int size;       //number of integer values in elements 
private int head = 0;   //front of the queue 
private int tail = 0;   //rear of the queue 
private int count = 0;  //tracks number of integer values 
public static final int DEFAULT_CAPACITY = 8; //maximum capacity of elements[] 

public Queue() 
{ 
this(DEFAULT_CAPACITY); 
} 

public Queue(int capacity) 
{ 
elements = new int[capacity]; 
} 

//adds integers 
public void enqueue(int v) 
{ 
elements[tail] = v; 
tail = (tail + 1) % DEFAULT_CAPACITY; 
count++; 
} 

//deletes integers
public void dequeue(int t){ 
t = elements[head]; 
head = (head + 1) % DEFAULT_CAPACITY; 
count--; 
} 

//check if element array is empty
public boolean isEmpty(){ 
return head == tail; 
} 

//check if element array is full
public boolean isFull(){ 
return (tail + 1) % DEFAULT_CAPACITY == head; 
} 

public int getSize(){ 
return this.size; 
} 

public String toString()
{ 
return("head--> " + Arrays.toString(elements) + " -->tail"); 
}

public static void main(String[] args){ 

int num; 
Queue queue = new Queue(); 
Scanner input = new Scanner(System.in); 

num = input.nextInt(); 

while(!queue.isFull()) 
{ 
queue.enqueue(num); 
num = input.nextInt(); 
} 
System.out.println(queue); 
} 
}

Your isFull methods looks suspicious.. what's wrong with count == elements.length

Also your code assumes the array is the default size (eg lines 34, 45). What happens if you try a queue of any other size ?

Well for my code the default capacity is 8, which is the maximum size for the queue.

Yes, but if you try
Queue queue = new Queue(6);
or
Queue queue = new Queue(10);
you will have problems, becuase the code asssumes 8.

Hi,

JamesCherill is right, you must use the size variable not the DEFAULT_SIZE, but you need to initialize it :

public Queue(int capacity)
{
    elements = new int[capacity];
    size = capacity;
} 

Annother probleme : before adding an element you must check if the queue is full or not, and before retreiving an element you must check if the queue is empty or not :

//adds integers
public void enqueue(int v)
{
    if(!isFull()){
        elements[tail] = v;
        tail = (tail + 1) % DEFAULT_CAPACITY;
        count++;
    }
}
//deletes integers
public void dequeue(int t){
    if(!isEmpty()){
        t = elements[head];
        head = (head + 1) % DEFAULT_CAPACITY;
        count--;
    }
} 
This article has been dead for over six months. Start a new discussion instead.