【问题标题】:toString method in circular array queue循环数组队列中的 toString 方法
【发布时间】:2015-04-30 00:59:07
【问题描述】:

我需要创建一个允许用户“环绕”数组的循环数组队列。我的老师检查了入队和出队方法,但我无法正确打印队列。

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

这也是我的客户端类。我将 toString 方法更改为用户 Jyr 建议的方法,但它仍然无法正确打印。我在客户端类中实现它时可能会出错。

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;
        }
    }

}

【问题讨论】:

  • 你到底有什么麻烦
  • 请你的老师教你单字符变量名是不好的做法(很少有例外)。 ;-) 另外,对于多个串联,请考虑使用StringBuilder
  • 为什么(以及何时)不能正确打印?请清楚并给出一个对你不起作用的测试用例。
  • 当我将项目排入数组(如 a、b、c)一直到 i 时,它会正确输出所有内容,因为它还没有引发完整的队列异常。但是当我希望它环绕并将 a 替换为 j 等等时,它会抛出异常但不会打印出显示它环绕。所以不是得到 [ j b c d e f g h i] ,我仍然得到 [ a b c d e f g h i]。
  • 您不想显示“环绕”(在打印中)。环绕仅用于填充数组中的null 值。所以它也不应该“替换”元素。现在,想象三个人排队等候。 [p1 p2 p3](队列大小:4)。现在假设他们都得到了他们需要的东西并离开了队列。此时,rear 变量等于 3。现在,队列中出现了三个新人。 rear 变量现在为 2,我们“环绕”。但这并不意味着我们应该打印 [p5 p6 p4],因为这是不正确的,因为第 4 个人在第一个位置。

标签: java arrays queue


【解决方案1】:

我相信你把事情复杂化了。你想要的是从f(例如i = f)开始,然后向上移动一个,但是既然我们可以环绕,我们应该向上移动(i + 1) % capacity。我们继续这样做直到我们到达终点(例如r)。在我们进入这个循环之前,我们应该验证队列不为空(以防止错误)。如果它实际上是空的,我们只需返回一个带有两个括号的String。所以你的代码看起来有点像这样;

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
}

或不同的方法(关于括号和逗号的打印);

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 + "]";

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多