Search code examples
javaqueue

i write a code to implement queue using arays in java. But it shows me wrong output


i write a code to implement queue using arays in java. But it shows me wrong output. The output should be 2 , 3 , 4 But output showed is 0 , 2 , 3 , 4.

my question was over here. But this stupid site algorithm says that your question contain mostly code. But if i finished writing my problem then how can i write more words to it. Therefore i am writing these sentences.

import java.util.*;
public class first {
  public static class queque{
    static int arr[];
    static int size;
    static int rear;
    queque(int n){
       arr = new int[n];
        size=n;
       int rear = -1;
    }
    public static boolean isEmpty(){
        return rear==-1;
    }`your text`
    public static void add(int data){
     if(rear == size-1){
        System.out.println("queue is full")`your text`;
     } 
     rear++;
     arr[rear]=data;
    }
    public static int remove(){
        if(isEmpty()){
            System.out.println("empty queue");
            return -1;
        }
        int front = arr[0];
        for(int i=0;i<rear;i++){
            arr[i]=arr[i+1];
        }
        rear--;
        
        return front;
    }
    public static int peek(){
        if(isEmpty()){
            System.out.println("empty queue");
            return -1;
        }
        return arr[0];
    }
  }
  public static void main(String[] args) {
    queque q = new queque(5);
    q.add(2);
    q.add(3);
    q.add(4);
    while(!q.isEmpty()){
        System.out.println(q.peek());
        q.remove();
    }
  }
 }

Solution

  • You have issue on this line

    int rear = -1;
    

    change it to

    rear = -1;