2017-05-01 1 views
0

나는 (고등학교) 주어진이 과제에 문제가 있습니다. 그것은 숫자 추측 게임이고 나는 이미 그것의 최대량을 얻었다, 그러나 그는 우리가 장치에 범위의 범위를두기 바란다. 예 출력은 다음과 같습니다 10번호 추측 프로그램 문제 Java

기타, 기본적으로 컴퓨터가 선택 할 수의 특정 범위를 선택 : 4

이 상한 입력 :

가 하한을 입력합니다. 나는 그가 원하는 것을하는 방법을 이해할 수 없기 때문에 단지 set range (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

, 두 가지 옵션이 있습니다 :

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

너는 나를 때렸다. 거의 동일한 솔루션을 준비했지만 먼저 게시했습니다.) : 귀하의 대답이 정확하기 때문에 아직 투표 할 것입니다. – CodingNinja

+0

저를 도와 주셔서 감사합니다! –

0

당신이해야하는 범위를 설정하기 위해 사용자를 원하는 경우 :

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; 

또는 1.7 이상 자바

당신이 범위의 사용자에게 또 다른 라인을 구현

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