2017-05-01 55 views
0

我遇到了這個任務的麻煩,我已經給了(高中)。這是一個猜數字的遊戲,我已經把它的大部分內容都放下了,但他希望我們在控制檯上放一些數字。一個例子輸出爲:猜數程序問題Java

輸入下限:4

輸入上限:10

等,基本上選擇你想要的計算機以供選擇號碼的特定範圍。我只能在一個設定的範圍內編碼(1-1000),因爲我無法弄清楚如何去做他想做的事情。這裏是我的代碼:

import java.util.Scanner; 


public class Game { 
    public static void main(String[] args) { 
     int randomNumber; 
     randomNumber = (int) (Math.random() * 999 + 1);   
     Scanner keyboard = new Scanner(System.in); 
     int guess; 
do { 
      System.out.print("Enter a guess (1-1000): "); 
      guess = keyboard.nextInt(); 

    if (guess == randomNumber) 
    System.out.println("Your guess is correct. Congratulations!"); 
    else if (guess < randomNumber) 
     System.out.println("Your guess is smaller than the secret number."); 
    else if (guess > randomNumber) 
System.out.println("Your guess is greater than the secret number."); 
     } while (guess != randomNumber); 
    } 

}

如果你嘗試它,它也真的很難反正玩。我會感謝一些幫助,謝謝!

+4

你覺得這種表達是這樣做的:'(INT)(的Math.random()* 999 + 1)'?你會如何改變它來獲得另一個範圍? – Henry

回答

6

有效範圍內的隨機數,你有兩個選擇:

Random rand = new Random(); 
// nextInt is normally exclusive of the top value, 
// so add 1 to make it inclusive 
int randomNum = rand.nextInt((max - min) + 1) + min; 

或者在Java 1.7或更高版本:

int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); 
+0

你打敗了我。我準備好了幾乎相同的解決方案,但是您先發布。 ):我仍然會投票,因爲你的回答是正確的 – CodingNinja

+0

感謝您花時間幫助我! –

0

如果你想要用戶設置您需要的範圍內實施另一條線,您要求用戶輸入範圍

Scanner min= new Scanner(System.in);Scanner max = new Scanner(System.in);

然後在這行代碼randomNumber = (int) (Math.random() * 999 + 1);,你現在可以設置你會與用戶輸入喜歡的範圍random.nextInt(max - min + 1) + min

+0

非常感謝! –

0
import java.util.Scanner; 
public class Game { 
public static void main(String[] args) { 
    Scanner keyboard = new Scanner(System.in); 
    System.out.println("enter minimum"); 
    int min= keyboard.nextInt(); 
    System.out.println("enter maximum"); 
    int max= keyboard.nextInt(); 
    int randomNumber= (int) (Math.random()* max + min); 
    int guess; 
    do { 
    System.out.print("Enter a guess (1-1000): "); 
    guess = keyboard.nextInt(); 

    if (guess == randomNumber) 
     System.out.println("Your guess is correct. Congratulations!"); 
    else if (guess < randomNumber) 
     System.out.println("Your guess is smaller than the secret number."); 
    else if (guess > randomNumber) 
     System.out.println("Your guess is greater than the secret number."); 
    } while (guess != randomNumber); 
    } 
} 
+0

感謝你們,你們都非常樂於助人! –

+0

你非常歡迎! – CrazyGal