【发布时间】:2019-03-28 05:15:32
【问题描述】:
程序需要能够将人员输入队列并跟踪他们。用户有 3 个选项“A”将新人(int)输入队列,“N”让队列被处理,“Q”退出队列,然后显示队列中有多少人.我不太清楚如何循环和跟踪。
package pkg3650queue;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner; // Import the Scanner class
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Queue<Integer> line = new LinkedList<Integer>();
Scanner input = new Scanner(System.in);
Scanner addperson = new Scanner(System.in);
String option;
do {
System.out.println("Type A to add a person to the line (# of requests)\n"
+ "Type N to do nothing and allow the line to be processed\n"
+ "Type Q to quit the application\n");
option = input.nextLine();
if(option.equalsIgnoreCase("A")) {
System.out.println("Enter a number to add a person to the line: ");
int addtoLine = addperson.nextInt();
line.add(addtoLine);
System.out.println(line);
System.out.println("There are " + line.size() + " people in the queue");
} else if (option.equalsIgnoreCase("N")) {
if(line.isEmpty()){
System.out.println("There are no elements in the line to be processed");
System.exit(0);
}
else{
int requestsProccessed = line.remove();
System.out.println(requestsProccessed);
System.out.println(line);
System.out.println("There are " + line.size() + " people in the queue");
}
}
} while (!option.equalsIgnoreCase("Q"));
System.out.println("Q was chosen. The number of ppl in this queue are " + line.size());
}
}
【问题讨论】:
-
与您的问题无关,但为了简化您的代码,您可以使用
option.equals("q") || option.equals("Q")而不是option.equalsIgnoreCase("q")。见corresponding doc -
您可以将所有代码(从问题的显示到结尾)放入一个循环中。使用布尔标志作为循环的条件。当用户输入
q时,将标志设置为 false。