Member 14090929 Ответов: 2

Думаю, программа количество


Проблема, с которой я сталкиваюсь, заключается в том, что переменная, которую я уже объявил сверху, не распознается снизу. Все переменные внизу, такие как numGames, totalGuesses, bestGuesses, которые я уже объявляю, не распознаются.
Я пишу этот код на java.


пакет guess2;
import java.util.*;
public class Guess2 {
    public static final int MAX_Number = 100;
    public static void main(String[] args) {
        
        Scanner console = new Scanner(System.in);
        giveIntro();
        int numGames = 0;
        int totalGuesses = 0;
        int bestGuesses = 9999;
        String again = "y";
        while (again.toUpperCase().startsWith("Y")) {
            int guesses = playGame(console);
            if (guesses < bestGuesses) {
                bestGuesses = guesses;
            }
            totalGuesses += guesses;
            numGames++;
            System.out.print("Do you want to play again? ");
            again = console.next();
        }
        reportResults();
    }

        
    
        
        
    
    //Introduces the game
    public static void giveIntro() {
        System.out.println("This program allows you to play a guessing game");
        System.out.println("I will think of a number between 1 and");
        System.out.println("100 and will allow you to guess until");
        System.out.println("you get it. For each guess, I will tell you");
        System.out.println("whether the right answer is higher or lower");
        System.out.println("than your guess");
    }
    
    //play one game with the user. return the number of guesses
    public static void playGame(){
        System.out.println("I'm thinking of a number between 1 and 100");
        System.out.println("Your guess?");
        Scanner console = new Scanner(System.in);
        int guess = 0;
        Random random = new Random();
        int answer = random.nextInt(MAX_Number);
        int numGuesses = 0;
        while (guess != answer) {
            numGuesses++;
        if (guess < answer) {
            System.out.println("the number is higher");
        if (guess > answer) {
            System.out.println("the number is lower");
        }
         
    }
    if (numGuesses == 1) {
        System.out.println("You got it right in 1 guess");
    } else {
        System.out.println("You got it right in "  + numGuesses + " guesses");
        
    }    
    return numGuesses;
        }
    public static void reportResults(){
        System.out.println("Overall result:");
        System.out.println("total games = " + numGames);
        System.out.println("total guesses = " + totalGuesses);
        double average = (double) totalGuesses / numGames;
        System.out.println("guesses/games = " + round1(average));
        System.out.println("best game = " + bestGuesses);
        
                
        
    }
}


Что я уже пробовал:

Я также пытаюсь выяснить, как вернуть значение для NumGuesses.

2 Ответов

Рейтинг:
1

OriginalGriff

Во-первых, сделайте правильный отступ, чтобы ваш код было легче читать, и стало очевидно, в чем проблема:

//play one game with the user. return the number of guesses
public static void playGame ()
{
    System.out.println ("I'm thinking of a number between 1 and 100");
    System.out.println ("Your guess?");
    Scanner console = new Scanner (System.in);
    int guess = 0;
    Random random = new Random ();
    int answer = random.nextInt (MAX_Number);
    int numGuesses = 0;
    while (guess != answer)
    {
    numGuesses++;
    if (guess < answer)
    {
        System.out.println ("the number is higher");
        if (guess > answer)
        {
            System.out.println ("the number is lower");
        }
    }
    if (numGuesses == 1)
    {
        System.out.println ("You got it right in 1 guess");
    }
    else
    {
        System.out.println ("You got it right in " + numGuesses + " guesses");
    }
    return numGuesses;
}
Вам не хватает закрывающей скобки для if (guess < answer) состоянии!

Всегда делайте отступы в коде правильно - это значительно облегчает понимание подобных проблем!


Рейтинг:
1

CPallini

Логика игры ошибочна. Так и должно быть:

public static  int playGame()
   {
       System.out.printf("I'm thinking of a number between 1 and %d\n", MAX_Number);

       int guess = 0;
       Random random = new Random();
       int answer = random.nextInt(MAX_Number)+1;
       int numGuesses = 0;
       do
       {
         numGuesses++;
         System.out.println("Your guess?");
         Scanner console = new Scanner(System.in);
         guess = console.nextInt();
         if  (guess < answer)
         {
           System.out.println("the number is higher");
         }
         else if ( guess > answer)
         {
           System.out.println("the number is lower");
         }
       }
       while ( guess != answer);
       if (numGuesses == 1)
         System.out.println("You got it right in 1 guess");
       else
         System.out.println("You got it right in "  + numGuesses + " guesses");

     return numGuesses;
   }