2014-05-19 50 views
0

嘿傢伙我有一個問題。我正在嘗試編寫一個豬骰子游戲,並且在程序的掃描器部分遇到問題,我要求用戶是否要繼續玩遊戲。該程序應該要求用戶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;  
} 
} 

回答

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使讀取來自現有行本身的輸入以及您的問題給用戶。

+0

在if/else之前,他已經將getAnswer聲明爲String。不需要重新聲明getAnswer作爲字符串了。它最終會出現錯誤。 – Sky

+0

如果我們重新聲明,那麼只有錯誤出現,但爲什麼他需要在if/else之前聲明?我建議他在if(隨機> 1)塊內直接聲明和指定內部塊。當我們需要外部變量時,如果塊只在之前聲明它,如果是好的,否則它最好的方法在塊內部聲明。 –