扫描仪对象出现问题以及执行它的位置

时间:2014-05-19 04:33:26

标签: java math

嘿伙计我有个问题。我试图写一个猪骰子游戏,我在程序的扫描仪部分遇到问题,我问用户是否要继续玩游戏。程序应该让用户y或n玩,但我似乎无法让我的程序在正确的行上读取用户输入并将用户信息转发给程序,所以我的if / else语句可以验证或使其无效。该程序还没有完成,我只是试着在继续之前解决这个问题。谢谢你的帮助!

以下是代码,我遇到问题的部分是名为takeTurn的部分。

import java.util.*;
public class PigDice {
// when a player reaches this number, they win
public static final int WINNING_SCORE = 50; 

public static final int DIE = 6; // sides on a die. 

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

    String winner = playGame( keyboard, rand );
    System.out.println( winner + " wins!" );
}
public static String playGame( Scanner scanner, Random rand ) {

    int score1 = 0; // player 1's score 
    int score2 = 0; // player 2's score 

    // play till someone wins
    while ( score1 < WINNING_SCORE && score2 < WINNING_SCORE ) {
        score1 += takeTurn( scanner, rand, 1, score1 );
        System.out.println( "Player 1 score: " + score1 );
        System.out.println( "***************************" );
        if ( score1 < WINNING_SCORE ) {   
            score2 += takeTurn( scanner, rand, 2, score2 );
            System.out.println( "Player 2 score: " + score2 );
            System.out.println( "***************************" );
        }
    }
    if ( score1 >= WINNING_SCORE ) {
        return "Player 1";
    }
    else {
        return "Player 2";
    }
}

public static int takeTurn( Scanner scanner, Random rand, int player, int score ) {
    int random = rand.nextInt(DIE)+ 1;
    System.out.println("Player " + player + " rolls: " + random);
    int firstRoll = random;
    int roundTotal = 0;
    String getAnswer = scanner.nextLine();

    if ( random > 1) {
        System.out.println( "Player " + player + " total for this round: " + firstRoll);
        roundTotal += firstRoll;
        System.out.print("Roll again? (y or n) : " + getAnswer);
        System.out.println();
        if ( "y".equalsIgnoreCase(getAnswer)) {
            System.out.println("Player " + player + " rolls: " + random);

        }else if ( "n".equalsIgnoreCase(getAnswer)) {
            System.out.println("Player " + player + " rolls: " + random);
        } 
    }else {
        System.out.println("Player " + player + ": turn ends with no new points.");
        System.out.println("Player " + player + " score: " + score);
    }     


    return WINNING_SCORE;    
} 
}

1 个答案:

答案 0 :(得分:0)

您已放置scanner声明String getAnswer = scanner.nextLine();

之前要求用户在takeTurn()方法中再次滚动问题。

所以在向用户询问问题之后如下所述

 System.out.println("Roll again? (y or n) : ");

  String getAnswer = scanner.nextLine();

并确保在执行println

时使用print而不只是System.out.println("Roll again? (y or n) : ");

println使用户输入从新行读取而

print会将现有行的输入以及您的问题读取给用户。