Hi everyone i am trying to implement a circular array, but something is not exactly right. I am not sure if is in the add method or display. When you run the debugger, the numbers are there but i cant get them in order. Please could you have a look and give me a feedback. Thank you.
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
Queue q1 = new Queue();
int choice = 0;
do
{
System.out.println ("Menu:");
System.out.println ("1: Add");
System.out.println ("2: Remove");
System.out.println ("3: Display");
System.out.println ("4: Exit");
System.out.print ("\nChoice: ");
choice = input.nextInt ();
switch ( choice )
{
case 1:
System.out.print ("\nEnter a number: ");
int num = input.nextInt ();
q1.add (num);
break;
case 2:
q1.remove ();
break;
case 3:
q1.display ();
break;
case 4:
System.out.println ("Good Bye");
break;
default:
System.out.println ("Wrong choice!");
break;
}
} while ( choice != 4 );
}
}
public class Queue {
private final int SIZE;
private int first;
private int last;
private int[] q;
public Queue ()
{
SIZE = 5;
q = new int[ SIZE ];
first = 0;
last = 0;
}
public boolean isFull ()
{
return last == SIZE;
}
public boolean isEmpty ()
{
return last == first;
}
public void add (int x)
{
if ( ! isFull () )
{
q[ ( first + last ) % q.length ] = x;
last ++;
} else
{
System.out.println ("\nThe queue is full!");
}
}
int remove ()
{
int x = 0;
if ( ! isEmpty () )
{
x = q[ first ];
first = ( first + 1 ) % q.length;
last --;
} else
{
System.out.println ("The queue is empy");
}
return x;
}
public void display ()
{
if ( ! isEmpty () )
{
for ( int i = first; i < SIZE; i ++ )
{
System.out.println (q[ i ]);
}
} else
{
System.out.println ("The queue is emptry");
}
}
It worked pretty well. Can you be more specific about your error ?
add() should only update last
. remove() should only update first
. add() needs to prevent the queue from going full, or the code needs to use a count of elements in the queue to check if the queue is full (versus empty, since last == first if either empty or full), in which case add() needs to prevent queue overflow. add() could return a code to indicate if add() was successful (no overflow) or if it failed (overflow). add() could optionally return a third code value to indicate that the queue was previously empty, in case some special action is needed when a queue goes from empty to non-empty.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.