首页 > 代码库 > 待解:Array; Queue

待解:Array; Queue

 1 package com.java7; 2 /* 3  * Try This 5-2 4  * A queue class for characters. 5  */ 6 class Queue { 7     char q[]; // this array holds the queue 8     int putloc, getloc; // the put and get indices 9     10     Queue(int size) {11         q = new char[size+1]; // allocate memory for queue12         putloc = getloc = 0;13     }14     15     // put a character into the queue16     void put(char ch) {17         if(putloc==q.length-1){18             System.out.println(" - Queue is full.");19             return;20         }21         22         putloc++;23         q[putloc] = ch;24     }25     26     // get a character from the queue27     char get() {28         if(getloc == putloc) {29             System.out.println(" - Queue is empty.");30             return (char) 0;31         }32         33         getloc++;34         return q[getloc];35     }36 }37 38 //Demonstrate the Queue class.39 class QDemo {40     public static void main(String[] args) {41         Queue bigQ = new Queue(100);42         Queue smallQ = new Queue(4);43         char ch;44         int i;45         46         System.out.println("Using bigQ to store the alphabet.");47         // put some numbers into bigQ48         for(i = 0; i < 26; i++)49             bigQ.put((char) (‘A‘ + i));50         51         // retrieve and display elements from bigQ52         System.out.print("Contents of bigQ: ");53         for(i = 0; i < 26; i++) {54             ch = bigQ.get();55             if(ch != (char) 0) System.out.print(ch);56         }57         58         System.out.println("\n");59         60         System.out.println("Using smallQ to generate errors.");61         // Now, use smallQ to generate some errors62         for(i = 0; i < 5; i++) {63             System.out.print("Attempting to store " + (char) (‘Z‘ - i));64             smallQ.put((char) (‘Z‘ - i));65             System.out.println();66         }67         System.out.println();68         69         // more errors on smallQ70         System.out.print("Contents of smallQ: ");71         for(i = 0; i < 5; i++) {72             ch = smallQ.get();73             74             if (ch != (char) 0) System.out.print(ch);75         }76     }77 }

执行结果:

Using bigQ to store the alphabet.

Contents of bigQ: ABCDEFGHIJKLMNOPQRSTUVWXYZ

 

Using smallQ to generate errors.

Attempting to store Z

Attempting to store Y

Attempting to store X

Attempting to store W

Attempting to store V - Queue is full.

 

 

Contents of smallQ: ZYXW - Queue is empty.

 

 

练习2:尝试修改Queue,以使其存储其他类型的对象。

待解:Array; Queue