2017-12-16 1 views
-2

이것은 간단한 숫자 추측 게임입니다. 사용자가 원하는 숫자를 입력해야합니다. 나는 2 ~ 3 번 0을 넣으려고했는데 그것은 맞았습니다. 그러나 그것은 항상 난수로 0을 얻습니다. 이 문제의 해결책은 무엇이 될 수 있습니까?왜 난수가 항상 0입니까?

class Main { 

    static int random; 
    static Scanner userInput = new Scanner(System.in); 

    public static void main(String[] args) { 
     int guessResult = 1; 
     int randomGuess = 0; 

     while (guessResult != -1) { 
      System.out.println("Guess a number between 0 and 50 : "); 

      randomGuess = userInput.nextInt(); 

      guessResult = checkGuess(randomGuess); 
     } 

     System.out.println("Yes the random number is " + randomGuess); 
    } 

    public static int getRandomNum() { 
     random = (int) (Math.random() * 50); 
     return random; 

    } 

    public static int checkGuess(int g) { 
     if (g == random) { 
      return -1; 
     } else { 
      return g; 
     } 
    } 
} 
+5

내가 (getRandomNum'의 사용을 볼 수 없습니다)' – matoni

+0

고마워. –

답변

0

getRandomNum 메서드는 호출하지 않습니다. 인쇄하려는 값 (randomGuess)은 System.in의 값입니다.

static int random; 

에서

0

는 무작위로 번호가 설정되어 있지 않습니다.

그래서 당신은 전화를 필요

Random rn = new Random(); 
random = rn.nextInt(51); 

(임의 nextInt 호출 배타적, 그래서 당신은 더 의지 할)

0
public class Number_game 
{ 
static int random; 
static Scanner userInput = new Scanner(System.in); 

public static void main(String[] args) 
{ 
    int guessResult = 1; 
    int randomGuess = 0; 

     System.out.println("Guess a number between 0 and 50 : "); 
     randomGuess = userInput.nextInt(); 
     guessResult = checkGuess(randomGuess); 
     System.out.println("The random number is "+guessResult); 
} 

public static int checkGuess(int g) 
{ 
    random = (int)(Math.random()*50); 
    if(g==random) 
    { 
    return g; 
    } 
    else 
    { 
    return random; 
    } 
} 

} 



Try This code 
관련 문제