How to make int counter go down when answer is wrong - java

Im making a player 2 guesses player 1's number game. Ive made an int counter thats == 10 and is meant to go down everytime player 2 gets answer wrong. I cant get it to work and i need help on how to make this. Youll see what i mean...
package guessMain;
import java.awt.*;
import java.util.Scanner;
public class GuessCodeSource {
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else if (answer <= 100){
System.out.println("Guess in the space below.");
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
}else if (guess != answer);
for (int counter = 10; counter-=1);
System.out.println("You have " + count + " of guesses left");
}
}
}

To make reduce a number by one, use the decrement operator.
For example,
counter--;
would subtract one from the counter.
If you want to subtract more than one, you can use the "-=" operator in the following manner:
counter -= 2;
So, in your code, in the final else if block, you could change the code to the following to reduce "counter" by 1.
else if (guess != answer) {
counter--;
System.out.println("You have " + count + " of guesses left");
}
But, in your code, you never declare the variable counter. Somewhere, most likely at the top of your code, you want to create this variable. To create an Integer variable you do the following:
int counter = 10;
You asked how to LOOP as well, so here it is. Read the comments to gain understanding of what the code does. If you have more questions, ask below.
public static void main(String[] args) {
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
int guess = 0; // Create these variables up here to access them everywhere in "main"
int counter = 0;
boolean continueTheGame = true; // A boolean variable that holds ONLY either true or false
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
// A while loop will continue as long as a boolean expression is true.
// So, we create a boolean variable somewhere above called "continueTheGame"
// As long as this is true, the code INSIDE of the while loop's brackets will repeat.
// If the user has less than zero guesses left, we can set the variable to false,
// which will make the loop stop!
while (continueTheGame == true) { // The start of the while loop
if (answer >= 100) {
System.out.println("BUSTED! I said a number between 1 - 100!");
} else if (answer <= 100) {
System.out.println("Guess in the space below.");
guess = josh.nextInt();
}
if (guess == answer) {
System.out.println("CORRECT!!!!!");
} else if (guess != answer) {
counter--;
System.out.println("You have " + counter + " of guesses left");
if (counter > 0) { // If they have MORE than zero guesses left, loop again!
continueTheGame = true;
} else { // If they have zero guesses left, make it stop looping
continueTheGame = false;
}
}
}
// Once the loop ends, the code will start again here,
// because the bracket above is the final bracket of the WHILE loop
}

Okay, so here is the full functional main method you are looking for:
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else {
System.out.println("Guess in the space below.");
}
for (int count = 10; count>=0; count--) {
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
System.exit(0);
} else {
System.out.println("You have " + count + " of guesses left");
if (count == 0) {
System.out.println("Sorry, you lost, no more tries..");
System.exit(0);
}
}
}
josh.close();
}

Related

How to properly pass a variable?

Here is my code, this program is a simple number guessing game, in which the computer picks a random number between 1 and x (set within the program) and the user is to guess the number using feedback from the computer stating whether each guess is higher or lower than secret number.
The code consists of 4 methods, a main method in which several variables are declared after displaying instructions for playing. Then a while loop is setup to start a new game. 3 lines into the while loop, a method is called to start playing a new game, passing both the scanner/console and an integer called guesses (which is set to 0 each time this method is called).
This integer, guesses, increments by one each time the user makes a guess and should be returned at the end of the game method, but I cannot seem to figure out why it is not being returned. It needs to be returned so it can be passed to the results method to calculate the stats that will be displayed if the user decides not to play again.
Any help would be appreciated...
import java.util.*;
public class Guess {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction(); //required
int games = 0;
int newGame = 1;
int guesses = 0;
int maxguesses = 0;
int totalguesses = 0;
while (newGame == 1) {
String userNewGame = "";
games = games + 1;
Game(guesses,console); //required
if (guesses > maxguesses) {
guesses = maxguesses;
}
totalguesses = totalguesses + guesses;
System.out.print("Do you want to play again? ");
userNewGame = console.next();
System.out.println();
char first = userNewGame.charAt(0);
if ( first == 'Y' || first == 'y') {
newGame = 1;
}
else if ( first == 'N' || first == 'n') {
newGame = 0;
}
}
Results(games,totalguesses,maxguesses); //required
}
public static void Introduction() {
System.out.println("This program allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and 100");
System.out.println("and will allow you to guess until you get it.");
System.out.println("For each guess, I will tell you whether the");
System.out.println("right answer is higher or lower than your guess.");
System.out.println();
}
public static int Game(int guesses, Scanner console) {
Random rand = new Random();
int range = 100; //Change this value to set the range the computer will require to guess ie. 100 is 1 to 100 inclusive, 5 is 1 to 5 inclusive, etc.
int number = rand.nextInt(range) + 1;
guesses = 0;
int guess = -1;
System.out.println("I'm thinking of a number...");
while (guess != number) {
System.out.print("Your guess? ");
guess = console.nextInt();
guesses = guesses + 1;
if (guess < number) {
System.out.println("higher");
}
if (guess > number) {
System.out.println("lower");
}
if (guess == number) {
System.out.println("You got it right in " + guesses + " guesses");
System.out.println();
}
}
return guesses;
}
public static void Results(int games,int totalguesses,int maxguesses) {
System.out.println("Overall results:");
System.out.println(" total games = " + games);
System.out.println(" total guesses = " + totalguesses);
System.out.println(" guesses/game = " + totalguesses / games);
System.out.println(" max guesses = " + maxguesses);
}
}
There's a handful of things going on here, and all of them kind of build on one another.
You're not capturing the result of the value you get back from Game.
You're doing some very strange things with your variables, which reduces readability.
You're going to run into issues with your Scanner down the line, as you loop through this program.
Let's start with the low-hanging fruit. Game returns an int, but it's not being assigned anywhere. Ideally, it should be assigned to the value of guesses.
guesses = Game(guesses,console); //required
...except it doesn't really make sense to pass guesses in when:
we're reassigning it in main (don't worry, the Game method will have its own copy of guesses anyway since Java is pass by value)
you explicitly assign it to 0 inside of Game anyway
So instead, you want to remove that as an argument to your method.
guesses = Game(console);
And inside of Game, you can define your own guesses variable.
public static int Game(Scanner console) {
Random rand = new Random();
int range = 100; //Change this value to set the range the computer will require to guess ie. 100 is 1 to 100 inclusive, 5 is 1 to 5 inclusive, etc.
int number = rand.nextInt(range) + 1;
int guesses = 0;
int guess = -1;
System.out.println("I'm thinking of a number...");
while (guess != number) {
System.out.print("Your guess? ");
guess = console.nextInt();
guesses = guesses + 1;
if (guess < number) {
System.out.println("higher");
}
if (guess > number) {
System.out.println("lower");
}
if (guess == number) {
System.out.println("You got it right in " + guesses + " guesses");
System.out.println();
}
}
return guesses;
}
The last obvious issue I can see is one where you're using next(), but you're not quite clearing the buffer for a Scanner.
userNewGame = console.next();
// and inside of Game()
guess = console.nextInt();
This is a surprisingly common Scanner problem, and it's easy enough to work around.
userNewGame = console.next();
console.nextLine();
// and inside of Game()
guess = console.nextInt();
console.nextLine();
Alternatively, you could use nextLine instead and not deal with next() since they both return String. The difference being that next() doesn't consume the newline character generated by Return/Enter, and nextLine() does.
Instead of just calling the Guesses method, you should use the returned value to update your variable, like so:
guesses = Game(guesses,console); //required
If you want the maxguesses to hold the max amount of guesses (among all the games), then you should update your logic after the Game method is called like so,
if (guesses > maxguesses) {
maxguesses = guesses; // not guesses = maxguesses
}
This is the whole code I am posting which works fine I think. Check it out:
import java.util.*;
public class Guess {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction(); //required
int games = 0;
int newGame = 1;
int guesses = 0;
int maxguesses = 0;
int totalguesses = 0;
while (newGame == 1) {
String userNewGame = "";
games = games + 1;
guesses = Game(guesses,console); //required
if (guesses > maxguesses) {
maxguesses = guesses;
}
totalguesses = totalguesses + guesses;
System.out.print("Do you want to play again? ");
userNewGame = console.next();
System.out.println();
char first = userNewGame.charAt(0);
if ( first == 'Y' || first == 'y') {
newGame = 1;
}
else if ( first == 'N' || first == 'n') {
newGame = 0;
}
}
Results(games,totalguesses,maxguesses); //required
}
public static void Introduction() {
System.out.println("This program allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and 100");
System.out.println("and will allow you to guess until you get it.");
System.out.println("For each guess, I will tell you whether the");
System.out.println("right answer is higher or lower than your guess.");
System.out.println();
}
public static int Game(int guesses, Scanner console) {
Random rand = new Random();
int range = 100; //Change this value to set the range the computer will require to guess ie. 100 is 1 to 100 inclusive, 5 is 1 to 5 inclusive, etc.
int number = rand.nextInt(range) + 1;
guesses = 0;
int guess = -1;
System.out.println("I'm thinking of a number...");
while (guess != number) {
System.out.print("Your guess? ");
guess = console.nextInt();
guesses = guesses + 1;
if (guess < number) {
System.out.println("higher");
}
if (guess > number) {
System.out.println("lower");
}
if (guess == number) {
System.out.println("You got it right in " + guesses + " guesses");
System.out.println();
}
}
return guesses;
}
public static void Results(int games,int totalguesses,int maxguesses) {
System.out.println("Overall results:");
System.out.println(" total games = " + games);
System.out.println(" total guesses = " + totalguesses);
System.out.println(" guesses/game = " + totalguesses / games);
System.out.println(" max guesses = " + maxguesses);
}
}
Sample output:
This program allows you to play a guessing game.
I will think of a number between 1 and 100
and will allow you to guess until you get it.
For each guess, I will tell you whether the
right answer is higher or lower than your guess.
I'm thinking of a number...
Your guess? 10
higher
Your guess? 50
lower
Your guess? 40
lower
Your guess? 30
lower
Your guess? 20
lower
Your guess? 15
You got it right in 6 guesses
Do you want to play again? y
I'm thinking of a number...
Your guess? 50
higher
Your guess? 80
higher
Your guess? 90
lower
Your guess? 85
You got it right in 4 guesses
Do you want to play again? n
Overall results:
total games = 2
total guesses = 10
guesses/game = 5
max guesses = 6

How can I complete my number guessing game?

My program should execute these steps:
Generate random no from 0 to 100.
Display random no and ask user enter (h/l/c)? (user have to enter one of them).
If it is correct ask user if they like to play again (y/n)? (user must answer (y/n))
I was able to execute Question no.1. Question no.2, random no display but I am unable to type character (h/l/c). Also, I am not able to ask player if they want to play again or not?
Here is what I have done:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number;
int guess = 0;
int min = 0;
int max = 100;
int answer= (min+max);
number = (int) (Math.random() *100 +1);
System.out.println("Guess a number between 1 and 100.");
//Ask user to type higher 'h', lower 'l' and correct 'c'.
System.out.println("Is it " + number + " ?" + " (h/l/c): " );
//
guess = 50;
while (guess <= 7)
{
System.out.println( "It is: " + guess + "?" + "(h/l/c) : " );
//Type 'h' if guess is high, 'l' for low and 'c' for correct.
if(answer == 'h')
{
max = guess -1;
min = 0;
guess = ((max = min)/2) + min;
guess++;
} else if (answer == 'l')
{
max = 100;
min = guess + 1;
guess = ((max+min)/2);
guess++;
} else if (answer == 'c');
}
System.out.println("Great! Do you want to play again? (y/n): ");
if(answer == 'y')
{
System.out.println("Guess a number between 1 and 100.");
//else prompt another question with if else
} else{
System.exit(0);
}
}
}
Your program does not accept any user input about if the guess is too low or too high.
You declared "answer" with an equation so it should accept a number.
answer would require a char or String value.
answer = keyboard.nextChar(); //read a char
answer = keyboard.nextLine(); //read a String

Have trouble with a while loop and trying to terminate the program by a press of a letter

I have a problem with my program.
Program is a HILO game which requires the user to guess a number between a range of a generated number.
The problem is that once i press 0 on my keyboard, it reveals the random number, and essentially must end the loop and ask whether the user wants to continue or end the program. Instead, it continues the loop, and whenever I press a letter on the keyboard it shows me an Exception error which describes and input Miss Match. Can some one guide me on how to fix it?, maybe I wrote the program wrong, I tried multiple ways, it still doesn't work as it supposed to work.
Thank you.
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
EDIT 1:
This code is working perfectly for me i have tried running it:
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
int exit;
for (exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.next();
// HERE YOU ARE DOING THE WRONG THING
// What is the meaning of "not(!)" here ? !choice.equalsIgnoreCase("x")
// Remove "NOT(!)" from here your program will work as expected
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
else if (number > answer)
{
System.out.println("TOO HIGH");
}
else if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
// MADE CHANGES HERE
choice = input.next();
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
}
}
Please do copy-paste the code. Because it is working perfectly without any Exception..!!
My sample outputs:
SAMPLE 1:
Guess a number between 1 and 50 : 1
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 27
Enter x to continue to play or y to endgame
y
END OF GAME
SAMPLE 2:
Guess a number between 1 and 50 : 20
TOO HIGH
Guess a number between 1 and 50 : 19
TOO HIGH
Guess a number between 1 and 50 : 15
Your guess was correct
The number was: 15
You guess the number with: 3 guesses
Enter x to continue to play or y to endgame
x
A new numberGuess a number between 1 and 50 : 20
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 42
Enter x to continue to play or y to endgame
y
END OF GAME
Do let me know if there is any problem.
Well, if you wish to end a loop, you could use the break; command. It jumps out of a while or for loop. So you could use this if the number is 0:
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter 'x' to continue to play or y to endgame");
choice = input.nextLine();
if(choice == "y")
{
break;
}
and add:
if(choice == "y") {break;} to the very end of the while(!Loop) loop.
And with the time when the answer is correct, you set Loop to false, which means !Loop would evaluate to true. You should change Loop = false to Loop = true when they decide to continue the game.
a small modification
public class HILOGAME {
public static void firstGame() {
final int range = 50;
int answer;
int number;
int guessNum = 0;
String choice = "";
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
if (number == answer) {
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
} else {
System.out.println("you entered a wrong value");
System.out.println("do you really want to try again? press y to continue or other alphabet to exit");
choice = input.next();
playAgain(choice);
}
}
public static void playAgain(String choice) {
if (choice.equalsIgnoreCase("Y")) {
firstGame();
} else {
System.out.println("you chose to quit");
System.exit(0);
}
}

Issue with Java Guessing Game

I'm working on this guessing game for school. I've realized that at some point I deleted my while loop for the user's guess equalling the computer's random number and it has messed up the results of my program. I thought that I could just add a nested while loop, but that hasn't worked. I've been trying to figure this out for hours.
Any ideas how to add something like while (guess == number) to my code and keep it working?
/*
Programming Assignment #3: Guess
Peter Harmazinski
Week 8
Guessing Game
*/
import java.util.*;
public class Guess {
public static final int RANGE = 100;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
boolean again = true;
double guessesDividedByGames = 0;
int maxGuesses = 0;
int numGames = 0;
int numGuesses = 1;
int totalGuesses = 0;
Random rand = new Random();
int number = rand.nextInt(RANGE) + 1;
int guessTracker = 0;
while(again) {
getInstructions();
int guess = getGuess(console);
numGuesses = getHigherLower(guess, number, console);
totalGuesses += numGuesses;
again = playAgain(numGuesses, console);
numGames++;
if (numGuesses > maxGuesses) {
maxGuesses = numGuesses;
}
}
guessesDividedByGames = (double)totalGuesses / numGames;
getResults(numGames, totalGuesses, guessesDividedByGames, maxGuesses);
}
//Prints instructions for user
public static void getInstructions() {
System.out.println("This program allows you to play a guessing game");
System.out.println("I will think of a number between 1 and " + RANGE);
System.out.println("and will allow you to guess until you get it.");
System.out.println("For each guess, I will tell you whether the");
System.out.println("right answer is higher or lower than your guess");
System.out.println("");
}
//Allows the user to play again if first letter of input is "y" or "Y"
public static boolean playAgain(int guessesNum, Scanner console) {
boolean anotherTime = false;
System.out.println("You got it right in " + guessesNum + " guesses.");
System.out.println("");
System.out.print("Do you want to play again? ");
String repeat = console.next();
String[] yesOrNo = repeat.split("");
System.out.println("");
if (yesOrNo[0].equals("y") || yesOrNo[0].equals("Y")) {
anotherTime = true;
}
return anotherTime;
}
//Outputs the results if the user doesn't play again
public static void getResults(int gamesTotal, int guessesTotal, double guessesDividedByGames, int guessesMax) {
System.out.println("Overall results:");
System.out.println("\ttotal games\t= " + gamesTotal);
System.out.println("\ttotal guesses\t= " + guessesTotal);
System.out.println("\tguesses/game\t= " + guessesDividedByGames);
System.out.println("\tmax guesses\t= " + guessesMax);
}
//Tells the user whether the random number is higher or lower
//and then returns the number of guesses
public static int getHigherLower(int guess, int randomNumber, Scanner console) {
int guessIncreaser = 1;
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
return guessIncreaser;
}
//Asks the user to guess the random number
//then returns the guess
public static int getGuess(Scanner console) {
System.out.println("I'm thinking of a number...");
System.out.print("Your Guess? ");
int playerGuess = console.nextInt();
while (playerGuess < 1 || playerGuess > RANGE) {
System.out.println("Out of range, please try again.");
System.out.print("Your Guess? ");
playerGuess = console.nextInt();
}
return playerGuess;
}
}
The problem appears to be your getHigherLower method, specifically these two while blocks:
while (guess > randomNumber) {
System.out.println("lower");
guess = getGuess(console);
guessIncreaser++;
}
while (guess < randomNumber) {
System.out.println("higher");
guess = getGuess(console);
guessIncreaser++;
}
If the user guessed a number lower than randomNumber, then higher, both while blocks would be escaped. Instead, what you want is this:
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
}
else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
What you need is one big while loop not two little ones
while (guess != randomNumber) {
if (guess > randomNumber) {
System.out.println("lower");
} else {
System.out.println("higher");
}
guess = getGuess(console);
guessIncreaser++;
}
First off, I'm hesitant to just give you the answer in code since this is for a school project and we learn by challenging ourselves and actualizing solutions. But I'm willing to point you in the right direction.
1. getHigherLower()
As others have pointed out, your two while loops are set up to cause errors. For instance, if I first guess too low, and then too high, your method mistakenly tells me I guessed correctly. This is a big problem!
Random number = 63
Guess 1 = 34 (lower)
Guess 2 = 100 (higher)
Actually your program tells me my guess of "100" when the number is "63" is correct!
// 1st conditional check: 34 !> 63, so skips first while loop
while (guess > randomNumber) {
guess = getGuess(console);
}
// 1st conditional check: 34 < 63, so enters second while loop
// 2nd conditional check: 100 !< 63, so skips second while loop
while (guess < randomNumber) {
// guess now becomes 100, goes back to top of while loop to check condition again
guess = getGuess(console);
}
// returns and exits method here (program wrongly thinks user has guessed correctly!)
Note that you can do a
System.out.println("random number: " + number);
to test that you're actually guessing the random number correctly. You might look into some JUnit testing as well.
James Ko seems to have a good feel for a better method implementation.
2. playAgain()
You use an if statement to check if the first index in an array of strings equals "y" or "Y" but your program never continues. Why is this?
if (yesOrNo[?].equals("y") {
anotherTime = true;
}
You should consider whether user input is really being placed at the first index or not?
Hint: loop through the "yesOrNo" array and print out each index to see where the user input is being placed in the array.
for (int i = 0; i < yesOrNo.length; i++) {
System.out.println("String at index " + i + ": " + yesOrNo[i]);
}
Good luck and remember that testing is your friend!

How would I add "You got it right in ... guesses!"

I need to add "You got it right in ... guesses!" but I'm not exactly sure how. Can someone please explain to me how to do this in java?
I would like it to display a println at the end saying how many tries it took for the user to get the number correct.
import java.util.*;
public class prog210c
{
public static void main()
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
if(guess < randomNum)
{
System.out.println("Higher--Try Again");
}
else if(guess > randomNum)
{
System.out.println("Lower--Try Again");
}
else if(guess == randomNum)
{
System.out.println("Correct!");
break;
}
else
{
System.out.println("Enter a number between 1 and 100");
}
}
//System.out.println("You got it right in " + + " guesses");
} //end main
} //end class
Just create some int variable to store your number of attempts in and increment it every time you read in a guess.
int attempts = 0;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
attempts++;
/**
* The rest of your loop code here.
*/
}
System.out.println("You got it right in " + attempts + " guesses");
The simplest way to do this is declared a counter integer, and in your logic increment it every time the user attempts.
int guessCounter = 0;
while(true) // Also do not use an infinite while loop, have an expression that can be terminated
{
...obtain input
if(guess < randomNum)
{
...
guessCounter++;
}
else if (guess > randomNum){
....
guessCounter++;
}
System.Out.println("The number of attempts " + guessCounter);
}
You could do this by creating a variable to store the number of tries, like an int, and then add one to the int every time the user guesses, by using variable++:
public static void main(){
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int tries = 0;
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while(true){
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
//Rest of your code here
}
System.out.println("You got it right in " + tries + " guesses");
}
and if you want to go even above and beyond, you could make it so it says You got it right in 1 guess instead of it saying You got it right in 1 guesses, if the user gets the number correct on their first try. We can do this by using the ternary Java operator, which is pretty much a compact if-statement:
String s = (tries == 1 ? "guess" : "guesses");
What this is pretty much doing is: if this is true ? do this : else do this
Now we can change the You got it right in... part of your program to say guess instead of guesses if the user guesses the number on their first try:
String s = (tries == 1 ? "guess" : "guesses");
System.out.println("You got it right in " + tries + "" + s);

Categories

Resources