有没有办法跟踪元素并循环菜单?

问题描述 投票:0回答:1

该程序需要能够将人员输入队列并跟踪它们。用户有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());
}
}
java loops queue
1个回答
0
投票

你的意思是如何循环用户输入?你可以使用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());

注意我没有测试这段代码,但它应该让你走上正确的轨道。

另请注意,在这种情况下我们不需要System.exit(0),因为程序将自然结束。虽然有例外,但您通常不想使用System.exit(0),而是希望找到代码“完成自己”的方法。

© www.soinside.com 2019 - 2024. All rights reserved.