Question
my java code wont run (guessing game) (while loops, booleans, if/else) -it wont execute the part where if (choice.toLowerCase().equals(n)) { again = false; -beginning of
my java code wont run (guessing game) (while loops, booleans, if/else)
-it wont execute the part where "if (choice.toLowerCase().equals("n")) { again = false;"
-beginning of code-
import java.util.*; public class Guess { public static final int MAX = 100; public static void main(String[] args) { Scanner console = new Scanner(System.in); Random r = new Random(); intro(); int totalGames = 0; int totalGuesses = 0; int average = 0; int bestGame = 0; boolean again = true; while (again == true) { int games = startGame(console, r); totalGuesses += games; if (games < bestGame) { bestGame = games; } games++; System.out.print("Do you want to play again? "); String choice = console.next(); if (choice.toLowerCase().equals("n")) { again = false; } } report(totalGames, totalGuesses, bestGame); } public static int startGame(Scanner console, Random r) { System.out.println("I'm thinking of a number between 1 and " + MAX + "..."); int answer = r.nextInt(MAX) + 1; boolean again = true; int guessesPerGame = 0; while (again == true) { System.out.print("Your guess? "); int playersGuess = console.nextInt(); guessesPerGame++; if (playersGuess == answer) { System.out.println("You got it right in " + guessesPerGame + " guesses"); again = false; } else if (playersGuess > answer) { System.out.println("It's lower."); } else { System.out.println("It's higher."); } } return guessesPerGame; } public static void intro() { 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."); } boolean again = false; public static void report(int totalGames, int totalGuesses, int bestGame) { System.out.println("Overall results:"); System.out.println(" total games =" + totalGames); System.out.println(" total guesses =" + totalGuesses); System.out.println(" guesses/games =" + roundNumber(totalGuesses/totalGames)); System.out.println(" best game =" + bestGame); } public static double roundNumber(double number) { return (Math.round(number * 10)) / 10.0; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started