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

时间:2019-03-27 15:26:36

标签: java loops queue

该程序必须能够将人员输入队列并进行跟踪。用户有3个选项:“ A”将新人输入到队列中;“ 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());
}
}

1 个答案:

答案 0 :(得分: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),而是希望找到代码“完成自身”的方法。