所以我有一个简单的Queue实现,我一直试图为它做一个switch case语句。现在它工作得很好。我的问题是它会询问你是否要继续,但即使你按下" n" for" No"它仍将继续。
另一件事是我无法在case3中用随机数填充数组。
代码: 实施:
class Que{
private int size;
private int front = -1;
private int rear = -1;
private Integer[] queArr;
public Que(int size) {
this.size = size;
queArr = new Integer[size];
}
public void insert(int item) {
if(rear == size-1) {
System.out.println("queue is overflowing");
}
else if(front==-1) {
rear++;
queArr[rear] = item;
front = rear;
}
else {
rear++;
queArr[rear] = item;
}
}
public void delete() {
if(front == -1) {
System.out.println("queue is underflow");
}
else if(front==rear) {
System.out.println("removing "+queArr[front]);
queArr[front] = null;
front--;
rear--;
}
else {
System.out.println("removing "+queArr[front]);
queArr[front] = null;
for(int i=front+1;i<=rear;i++) {
queArr[i-1]=queArr[i];
}
rear--;
}
}
public void display() {
if(front==-1)
System.out.println("queue is empty");
else
{
System.out.println("queue is:");
for(int i=front;i<=rear;i++) {
System.out.print(queArr[i]+"\t");
}
}
}
}
测试:
import java.util.Random;
import java.util.Scanner;
public class TestQueue {
public static void main(String[] args) {
System.out.println("Hi user!");
Scanner scan = new Scanner(System.in);
System.out.println("please enter size of queue array");
int size = scan.nextInt();
Que que = new Que(size);
char ch;
do{
System.out.println("\nQueue operations \n");
System.out.println("1. insert");
System.out.println("2. delete");
System.out.println("3. random");
int choice = scan.nextInt();
switch(choice)
{
case 1: System.out.println("enter integer element to insert");
que.insert(scan.nextInt());
break;
case 2:que.delete();
break;
case 3: Random rand = new Random();
rand.nextInt(size);
break;
}
que.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
}
while(ch!='N' || ch!='n');
}
}
我还需要一些关于如何读出和显示数组中所有素数的指针。但这可能是不同讨论的主题。
我想我在测试结束时搞砸了while语句。
答案 0 :(得分:6)
while(ch!='N' || ch!='n');
始终为true(对于ch
的任何值)。
你需要
while(!(ch=='N' || ch=='n'));