2015-11-08 110 views
-1

我在計算我的代碼中發生了什麼有點麻煩(去圖) 我還沒有涉及到一些我最終的int值,但是我會在我能得到一些其他的問題。猜謎遊戲Java的問題

  1. 我想不通爲什麼改變correctGuess爲真後,我無法從我的用戶得到更多的輸入程序退出,以決定他們是否願意繼續玩下去了。

  2. 這應該需要從某人的電腦毫秒,並收集一個1-110之間的隨機數,但有時我得到負數,似乎無法弄清楚這是什麼問題。

任何幫助,將不勝感激......

import java.util.Scanner; 
import java.util.Random; 

public class GuessingGame { 
    private static final int MIN_NUMBER = 1; 
    private static final int MAX_NUMBER = 110; 
    private static final int EXIT_VALUE = -1; 
    private static final int MAX_GAMES = 256; 


    public static void main(String[] argv) { 
     System.out.println("*** You are playing the CSC110 Guessing Game ***"); 
     Scanner scanner = new Scanner(System.in); 

     int totalGames = 0; 
     int wonGames = 0; 
     int guess = 0; 

     boolean playing = true; 

     while (playing) { 
      boolean correctGuess = false; 
      totalGames++; 

      Random rg = new Random(System.currentTimeMillis()); 
      int n = MIN_NUMBER + rg.nextInt() % (MAX_NUMBER - MIN_NUMBER); 


      System.out.println("Pick a number between 1 and 110 (-1 to exit): "); 

      int numberOfTries = 0; 

      while (!correctGuess) 
      { 
       guess = scanner.nextInt(); 
       numberOfTries++; 
       System.out.print(numberOfTries); 

       if (guess == n) { 
        System.out.print("Congrats, it took you " + numberOfTries + " try/tries to get the right number!"); 
        System.out.print("Do you want to play again? (Yes/No)"); 
        correctGuess = true; 
       } 
       else if(guess != n && numberOfTries < 5) 
       { 
        System.out.println("nope... \n"); 
       } 

       else if(guess > n && numberOfTries >= 5) 
       { 
        System.out.print("Try something lower \n"); 
       } 
       else if(guess < n && numberOfTries >= 5) 
       { 
        System.out.print("Try something higher \n"); 
       } 
      } 
      String playAgain = scanner.nextLine(); 
      if(playAgain.equals("Yes")) 
      { 
       playing = true; 
      } 
      else 
      { 
       playing = false; 
      } 

     } 
    } 
} 
+0

嘗試'scanner.nextLine()'之前'字符串playAgain = scanner.nextLine();' –

+0

添加此來生成隨機數'詮釋N = ThreadLocalRandom.current()nextInt(1,110。 + 1);'第一個參數是包含性的,第二個是排他性的,這就是爲什麼你加上+1 – Jonah

回答

1

1:測試以下,它工作正常:

String playAgain = scanner.next(); 

您也可以考慮修改您的if語句如下:

if(playAgain.equalsIgnoreCase("Yes") || playAgain.equalsIgnoreCase("Y")) 

2:確保數字出來的最簡單方法是使用Math.abs()。

int n = Math.abs(MIN_NUMBER + rg.nextInt() % (MAX_NUMBER - MIN_NUMBER));