gpt4 book ai didi

Java:Switch case 的问题

转载 作者:行者123 更新时间:2023-11-29 06:58:15 25 4
gpt4 key购买 nike

<分区>

所以我有一个 Queue 的简单实现,我一直在尝试为它制作一个 switch case 语句。现在它工作得很好。我的问题是它会询问您是否要继续,但即使您按“n”表示“否”,它仍会继续。

另一件事是我无法在 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 语句。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com