在while循环中两次询问用户输入

时间:2018-07-31 14:16:02

标签: java while-loop user-input

我目前正在做一个Java项目。该项目涉及一个有关NHL Statistics的数据库,该数据库还涉及通过用户输入从数据库访问信息的位。我正在使用 while 循环在多种情况下要求用户输入,例如询问收到的处罚次数,进球数,积分等。特定部分,它要求用户输入他们想要的统计信息(得分,目标,助攻,点球,助攻,球员,俱乐部)。此后,如果用户键入 player 作为他们的选择,则系统应该询问用户他们希望查看哪些球员统计信息。问题在于,由于我是在用户第一次输入后使用 while 循环,因此该循环将被执行,并且程序将在播放器可以第二次输入之前结束。任何帮助将不胜感激,这是我的代码:

import java.util.Scanner;
import nhlstats.NHLStatistics;

public class NhlStatisticsPart2 {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.println("NHL statistics service");

        while (true) {
            System.out.println("");
            System.out.print("command (points, goals, assists, penalties, player, club, quit): ");
            String command = reader.nextLine();

            if (command.equals("quit")) {
                break;
            }

            if (command.equals("points")) {

                NHLStatistics.sortByPoints();
                NHLStatistics.top(10);

                // Print the top ten players sorted by points.
            } else if (command.equals("goals")) {
                NHLStatistics.sortByGoals();
                NHLStatistics.top(10);

                // Print the top ten players sorted by goals.
            } else if (command.equals("assists")) {
                NHLStatistics.sortByAssists();
                NHLStatistics.top(10);

                //  Print the top ten players sorted by assists.
            } else if (command.equals("penalties")) {
                NHLStatistics.sortByPenalties();
                NHLStatistics.top(10);
                //  Print the top ten players sorted by penalties.

            } else if (command.equals("player")) {
                System.out.println("Which player statistics?");

                NHLStatistics.searchByPlayer(command);



                // Ask the user first which player's statistics are needed and then print them.
            } else if (command.equals("club")) {
                // Ask the user first which club's statistics are needed and then print them.
                // Note: When printing statistics they should be ordered by points (so the players with the most points come first).
            }

        }

    }
}

这是我收到的消息:

command (points, goals, assists, penalties, player, club, quit): player
Which player statistics?

command (points, goals, assists, penalties, player, club, quit):

可以看出,该程序没有允许用户输入他们想要查看的球员统计数据,而是返回到先前的问题,而无需允许用户输入。有没有一种方法,用户可以在不执行循环的情况下回答问题(哪个玩家的统计信息?)?

1 个答案:

答案 0 :(得分:1)

那么您需要请用户输入播放器。因此,您需要使用扫描仪扫描另一个值。如果在if条件下执行此操作,则直到用户输入该值,该操作才会继续。

     .....
    } else if (command.equals("player")) {
        System.out.println("Which player statistics?");
        command = reader.nextLine();  //Read again from the input
        NHLStatistics.searchByPlayer(command);  //now use that second value
    }
     .......