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



程序需要能够将人员输入队列并跟踪他们。 用户有 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 processedn"
            + "Type Q to quit the applicationn");
    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 processedn"
                + "Type Q to quit the applicationn");
        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),而是想办法让代码"完成自己"。

最新更新