如何使用 switch 语句和扫描实用程序模拟商店队列?
How to make a simulation of a shop queue with switch statement and scan utility?
我必须使用扫描、切换和案例制作一个 Java 程序,在其中我可以使用命令“添加”添加一位客户并使用命令“删除”删除一位客户。
队列中的默认客户数是 5。如果客户数大于 8,它会打印出“这个队列太大。”如果少于 1 个客户,它会打印出“队列中没有人。”
我试着做了一些代码,但我不知道下一步该做什么。
import java.util.Scanner;
public class fronta {
public static void main(String[] args) {
System.out.println ("This queue has 5 people in it at the moment.");
Scanner scan = new Scanner(System.in);
boolean x = true;
String b = "ADD";
int a = 5;
b = scan.nextLine();
while(x){
switch (b) {
case "ADD":
System.out.println ("This queue has " + a + " people in it at the moment.");
b = scan.nextLine();
System.out.println ("This queue is too big");
break;
default:
case "EXIT":
System.out.println("End of simulation.");
x = false;
break;
}
}
}
}
我认为您需要如下内容:
public static void main(String[] args) {
boolean isExitRequested = false;
int queueSize = 5;
System.out.println ("This queue has "+queueSize+" people in it at the moment.");
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
String input = scan.nextLine();
switch (input){
case "ADD":
System.out.println ("This queue has " + queueSize++ + " people in it at the moment.");
if (queueSize > 8) {
System.out.println("This queue is too big");
}
break;
case "REMOVE":
if (queueSize == 0){
System.out.println("There's nobody in the queue.");
} else {
queueSize--;
}
break;
case "EXIT":
isExitRequested = true;
break;
default:
System.out.println("Unknown input: "+input);
}
if(isExitRequested)
break;
}
}
我必须使用扫描、切换和案例制作一个 Java 程序,在其中我可以使用命令“添加”添加一位客户并使用命令“删除”删除一位客户。
队列中的默认客户数是 5。如果客户数大于 8,它会打印出“这个队列太大。”如果少于 1 个客户,它会打印出“队列中没有人。”
我试着做了一些代码,但我不知道下一步该做什么。
import java.util.Scanner;
public class fronta {
public static void main(String[] args) {
System.out.println ("This queue has 5 people in it at the moment.");
Scanner scan = new Scanner(System.in);
boolean x = true;
String b = "ADD";
int a = 5;
b = scan.nextLine();
while(x){
switch (b) {
case "ADD":
System.out.println ("This queue has " + a + " people in it at the moment.");
b = scan.nextLine();
System.out.println ("This queue is too big");
break;
default:
case "EXIT":
System.out.println("End of simulation.");
x = false;
break;
}
}
}
}
我认为您需要如下内容:
public static void main(String[] args) {
boolean isExitRequested = false;
int queueSize = 5;
System.out.println ("This queue has "+queueSize+" people in it at the moment.");
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
String input = scan.nextLine();
switch (input){
case "ADD":
System.out.println ("This queue has " + queueSize++ + " people in it at the moment.");
if (queueSize > 8) {
System.out.println("This queue is too big");
}
break;
case "REMOVE":
if (queueSize == 0){
System.out.println("There's nobody in the queue.");
} else {
queueSize--;
}
break;
case "EXIT":
isExitRequested = true;
break;
default:
System.out.println("Unknown input: "+input);
}
if(isExitRequested)
break;
}
}