简体   繁体   中英

toString method in circular array queue

I need to create a circular array queue that allows the user to "wrap around" the array. The enqueue and dequeue methods were checked off by my teacher, but I'm having trouble getting the queue to print off correctly.

public class MyArrayQueue<E> implements QueueInterface<E> {

    public static final int CAPACITY = 10;  
    private int capacity; 
    private E q[]; //array of E 
    private int f; //front 
    private int r; //rear

    //constructor
    public MyArrayQueue() {
         this (CAPACITY);
    }

    //constructor
    public MyArrayQueue(int n) {
        capacity = n;
        q = (E[]) new Object[capacity];
    }

    public void enqueue(E obj) throws FullQueueException {
        if(size() == capacity - 1) { //cannot hold more than n-1
            throw new FullQueueException("Full queue exception.");
    }

        q[r] = obj; //insert object in end of the queue
        r = (r + 1) % capacity; //wrap around r

    }

    public E dequeue() throws EmptyQueueException {
        if (isEmpty())
            throw new EmptyQueueException("Empty queue exception.");

        E temp = q[f]; //retrieve the front object
        q[f] = null; //good programming practice

        f = (f + 1) % capacity; //wrap around f

        return temp;
  }

  public E front() throws EmptyQueueException {
      if (isEmpty()) 
          throw new EmptyQueueException("Empty queue exception.");

      return q[f]; //return the front object without removing it
  }

  public boolean isEmpty() {
      return (f == r);
  }

  public int size() {
      return (capacity - f + r) % capacity;
  }

  //fix this loop for homework assignment, make it wrap around
  public String toString() {
      if (isEmpty())
          return "[]";

      String result = "[";

      result += q[f];

      for (int i = (f+1) % capacity; i != r; i = (i+1) % capacity) {
          result += " " +q[i];
      }
      return result + "]";
  }

} //end class

Here is my client class as well. I changed the toString method to what user Jyr suggested, but it still doesn't print out properly. I might have some mistake implementing it in my client class.

public static void main(String[] args) {

    Scanner console = new Scanner(System.in);

    MyArrayQueue<String> list = new MyArrayQueue<>();

    int capacity;
    int CAPACITY = 10;
    String q[];

    for (int i = 0; i < CAPACITY; i++) {
        capacity = i;
        q = new String[i];
    }

    String name;

    boolean flag = true;
    int num;

    while (flag) {
        System.out.println();
        System.out.println("1 ----- enqueue");
        System.out.println("2 ----- dequeue");
        System.out.println("3 ----- front");
        System.out.println("4 ----- ouput elements in the queue");
        System.out.println("5 ----- isEmpty");
        System.out.println("6 ----- size");
        System.out.println("0 ----- exit");
        System.out.println();

        System.out.println("Enter a command: ");
        num = console.nextInt();
        System.out.println();

        switch(num) {
            case 1:
                try {
                    System.out.println("Enter a word to enqueue: ");
                    name = console.next();
                    list.enqueue(name); 
                }
                catch (FullQueueException e) {
                    System.out.println("Full Queue");
                }
                break;
            case 2:
                try  {
                    System.out.println(list.dequeue());
                }
                catch (EmptyQueueException e){
                    System.out.println("Empty Queue");
                }
                break;
            case 3:
                try {
                    System.out.println(list.front());
                }
                catch (EmptyQueueException e) {
                    System.out.println("Empty Queue");
                }
                break;
            case 4:
                System.out.println(list.toString());
                break;
            case 5:
                System.out.println(list.isEmpty());
                break;
            case 6:
                System.out.println(list.size());
                break;
            case 0:
                flag = false;
                System.out.println("Thank you for using this program. ");
                break;
            default:
                System.out.println("Invalid input.");
                break;
        }
    }

}

I believe you are overcomplicating things. What you want is to start at f (eg i = f ), and then move up by one, but since we can wrap-around, we should move up by (i + 1) % capacity . We keep on doing this until we reach the end (eg r ). Before we enter this loop we should verify that the queue is not empty (to prevent errors). If it actually turns out to be empty, we simply return a String with just the two brackets. So your code would look a little like this;

public String toString() {

    if (isEmpty()) return "[]";
    String result = "[";

    for (int i = f; i != r; i = (i+1)%capacity) {
        result += q[i] + ", ";
    }   

    return result.substring(0,result.length()-2) + "]";
    // a bit dirty but gets the job done
}

Or a different approach (regarding the printing of brackets and commas);

public String toString() {

    if (isEmpty()) return "[]";
    String result = "[";

    result += q[f];

    for (int i = (f+1)%capacity; i != r; i = (i+1)%capacity) {
        result += ", " + q[i];
    }   

    return result + "]";

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM