java - 有没有办法跟踪元素并循环菜单?
问题描述
该程序需要能够将人员输入队列并跟踪他们。用户有 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());
}
}
解决方案
你的意思是如何循环用户输入?您可以使用do-while
:
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")) {
// do something
} else if (option.equalsIgnoreCase("N")) {
// do something
}
// notice we don't need an if for 'Q' here. This loop only determines how many
// times we want to keep going. If it's 'Q', it'll exit the while loop, where
// we then print the size of the list.
} while (!option.equalsIgnoreCase("Q"));
System.out.println("Q was chosen. The number of ppl in this queue are " + line.size());
注意我没有测试这段代码,但它应该能让你走上正确的轨道。
另请注意,在这种情况下我们不需要 a System.exit(0)
,因为程序会自然结束。尽管有例外,但您通常不想使用System.exit(0)
,而是希望找到代码“完成自身”的方法。
推荐阅读
- sql - 验证代码中的 Pl/SQL 语法问题
- elasticsearch - ElasticSearch NEST 简单条款查询需要 .keyword
- windows - 如何使.exe文件的内容在记事本中不可读
- python - 如何仅将 df.str.replace() 用于完整匹配?
- javascript - 开发者工具中的 Vue 数组更新但不会重新渲染
- powershell - VSCode - 在单独的窗口中打开终端
- python - 无法使用 upload-symbols.py 将符号文件上传到 Flurry:Broken pipe>
- python - 如何查询集继承模型django?
- python - 导出 anaconda 环境的最佳方法,但还包括定制包?
- javascript - PHP Cookies(如果有的话)