2017-05-01 18 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); 
    } 

}

あなたがそれをしようとした場合、とにかくプレイするためにも、本当に難しいです。私はいくつかの助けに感謝します、ありがとう!

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以降で:

+4

: '(int型)(Math.random()* 999 + 1) '?あなたは別の範囲を得るためにそれをどのように変更しますか? – Henry

答えて

6

範囲の乱数については、次の2つの選択肢があり

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

関連する問題