Java - 代码在循环中重复

时间:2015-12-02 17:21:53

标签: java

我正在开发一个从命令行获取用户输入的程序。但是,当程序循环时,它会重复一些代码行(如下所示)。

我的问题是,对于循环的每次迭代超过第一次,它会跳过游戏标题并直接进入分数。

我如何防止这种情况发生?

p = System.out.print()

代码:

        for (int i = 0; i <= 10; i++) {
            if( i == 0) {
                p("Enter player: ");
                playerName = scan.nextLine();
            }           

            try {       
                gameName = "";
                score = 0;
                time = 0;

                p("Enter game: ");
                gameName = scan.nextLine();

                p("Enter score: ");
                score = scan.nextInt();

                p("Enter time: ");
                time = scan.nextInt();

                Game game = new Game(gameName, score, time);
                if (i == 0) {
                    textToPrint = playerName + "\r\n- - - - - - - - - - - - -\r\n" + game.getGame() + " : " + game.getScore() + " : " + game.getTime() + "\r\n";
                } else {
                    textToPrint = game.getGame() + " : " + game.getScore() + " : " + game.getTime() + "\r\n";
                }               
            } catch (InputMismatchException e) {
                p("You must enter an integer!");            
            }

            try {
                WriteFile data = new WriteFile("scores.txt");       
                data.WriteToFile(textToPrint);
            } catch (IOException e) {
                p("Something went wrong during printing: " + e.getMessage());

            }   
        }   

它在这里重复:

                p("Enter game: ");
                gameName = scan.nextLine();

                p("Enter score: ");
                score = scan.nextInt();

所以输出如下:

Enter game: Enter score:

任何想法都将不胜感激!

谢谢!

0 个答案:

没有答案