I have to make a Java program using scan, switch and cases in which I can add one customer with a command "add" and remove one customer with a command "remove".
The default number of customers in queue is 5. If the count of customers gets larger than 8 it prints out "This queue is too big." If there is less than 1 customer it prints out "There's nobody in the queue."
I tried to do some of the code, but I have no idea what to do next.
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;
}
}
}
}
I think you need somehting like below:
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;
}
}
Shoutout to Vasif for helping me with it.
import java.util.Scanner;
public class shoppingqueue {
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":
queueSize++;
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":
queueSize--;
System.out.println ("This queue has " + queueSize + " people in it at the moment.");
if (queueSize == 0){
System.out.println("There's nobody in the queue.");
}
break;
case "EXIT":
isExitRequested = true;
break;
default:
System.out.println("Unknown: "+input);
}
if(isExitRequested)
break;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.