2017-01-06 5 views
0

Я создаю угадающую игру на Java с помощью NetBeans. Игра угадывания позволяет пользователю угадать число от 1 до 10. Каждый раунд имеет 5 шансов угадать номер. В игре три раунда. После того, как пользователь закончит игру, статистика выводится с минимальным количеством догадок и максимальным количеством догадок.Угадающая игра с минимальными догадками, которые не используются в Java

Минимальные догадки не работают, и он всегда выводит 1. Прямо сейчас у меня есть программа, настроенная так, чтобы она отслеживала, сколько раз пользователь угадывает за раунд. После каждого раунда он сравнивает это значение с минимальным значением и максимальным значением. Значение minGuess устанавливается как 5, так как невозможно угадать более 5 раз. MaxGuess устанавливается как 1, так как они всегда будут угадывать один раз или более одного раза.

static void numberGuess(int guess, int randNum) {        //creating a method to check if the user has guessed the correct number or if the guess should be higher or lower 

if (guess < 0 | guess > 10) { 
    System.out.println("Please enter a valid number between 1 and 10."); 
} 
else if (guess == randNum) { 
    System.out.println("You guessed the number correctly"); 
} 
else if (guess < randNum) { 
    System.out.println("Guess is too low"); 
} 
else if (guess > randNum) { 
    System.out.println("Guess is too high"); 
} 




} 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    /*Rational: This program allows a user to guess a number between 1 and 10 five times per round. There are three rounds in one game. 
       The program then outputs the stats for the game. 
    */ 
    //declaration 
    int userGuess;   //creates a spot in memory for these variables 
    int numOfGuess = 0; 
    int invalidGuess = 0; 
    int minGuess = 5; 
    int maxGuess = 1; 
    int average; 

    Scanner Input = new Scanner (System.in); //creates an object in the scanner clas 
    //execution 
    System.out.println("Welcome to Super Guessing Game! Guess a random number between 1 and 10. There are three rounds with one guess each."); 
    loopOne:          //labels the loop as loopTwo 
    for (int x = 1; x <= 3; x= x + 1) {  //runs the loop for three rounds 
     System.out.println(" "); 
     System.out.println("Round " + x); 
     System.out.println("To exit the game at any point, enter a negative 1"); 
     System.out.println(" "); 

     int randNum; 
     randNum = 1 + (int)(Math.random() * ((10 - 1) + 1));  //generates the random number 


     loopTwo:          //labels the loop as loopTwo 
     for (int y = 1; y <= 5; y= y + 1) {    //runs the loop five times (five guesses per round) 
      numOfGuess = numOfGuess + 1;    //counts number of guesses user has made 
      System.out.println("Guess " + y + " out of 5"); 
      System.out.println("Please guess a number between 1 and 10: "); 
      userGuess = Input.nextInt(); 
      if (userGuess == -1){      //sentinel to let the user quit at any time 
      System.out.println("Thank you for playing"); 
      break loopOne;        //breaks out of the loops if the user wants to stop playing 
      } 

      numberGuess(userGuess, randNum);  //calls the numberGuess method 
      if (y < minGuess)     //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round 
       minGuess = y; 
      if (y > maxGuess)     //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round 
       maxGuess = y; 


      if (userGuess <1 | userGuess > 10) {  //keeps track of invalid guesses 
       invalidGuess = invalidGuess + 1; 
      } 

      if (userGuess == randNum) {   //exits the round if the user guesses correctly 
       break; 
      } 
     } 

    } 
    average = numOfGuess/3;    //calculates the average number of guesses 
    System.out.println("Thanks for playing!");  //outputs the following 
    System.out.println(""); 
    System.out.println("Number of Guesses Made: " + numOfGuess); 
    System.out.println("Average Number of Guesses: " + average); 
    System.out.println("Number of Invalid Guesses: " + invalidGuess); 
    System.out.println("Minimum Guesses Used: " + minGuess); 
    System.out.println("Maximum Guesses Used: " + maxGuess); 

} 

}

+0

Просто интересно, не '((10 - 1) + 1)' просто '10'? – user2004685

+0

Часть случайных чисел работает, это всего лишь минимальное количество догадок, которые не работают. –

+0

Да. Конечно. Мне просто интересно, есть ли какой-нибудь трюк в написании '10' вот так! :) – user2004685

ответ

0

у начинается с одного, и никогда не меньше, чем один, таким образом, minGuess всегда один.

for (int y = 1; y <= 5; y= y + 1) {    
    ... 
     if (y < minGuess)      
      minGuess = y; 
    ... 
    } 

Рассмотрите только обновление minGuess и maxGuess по успешной догадки.

+0

Спасибо за вашу помощь. Я попробую. –

+0

@Trebla, он уже начинает minGuess в 5. – Andreas

0

Ваше заявление не в том месте.

Ваш вопрос каждый раз. также, если пользователь не угадает правильный номер.

так просто поставить его в ур метод numberguess:

else if (guess == randNum) { 
System.out.println("You guessed the number correctly"); 
if (y < minGuess)     //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round 
    minGuess = y; 
if (y > maxGuess)     //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round 
    maxGuess = y; 
} 
+0

Спасибо за вашу помощь. Я попробую. –

Смежные вопросы