Here’s my code:
import java.util.Scanner;
import static java.lang.System.*;
public class GuessingGame
{
private int upperBound;
private int count, guess, num, pct;
public GuessingGame(int stop)
{
upperBound = stop;
}
public void setNum(int stop)
{
upperBound = stop;
}
public void playGame()
{
int count = 0;
int attempt = 1;
Scanner keyboard = new Scanner(System.in);
//upperBound = keyboard.nextInt();
num = (int)Math.random()*upperBound;
guess = 0;
out.println("Enter a number between 1 and " + upperBound);
guess = keyboard.nextInt();
count++;
if(guess != num)
attempt++;
do{
out.println("Enter a number between 1 and " + upperBound);
guess = keyboard.nextInt();
count++;
if(guess != num)
attempt++;
}while(guess != num);
pct = (count/attempt)*100;
}
public String toString()
{
String output="";
output = "It took you " + count + " tries to guess " + num + "\n you guessed wrong " + pct + "% of the time";
return output;
}
}
I know that it has to at some point guess has to be equal to num but the code never ends the current “game” but it seems to be infinitely looping when I use my example of 5 for the stop/upperBound
Here’s my runner class as requested:
import java.util.Scanner;
import static java.lang.System.*;
public class Lab10e
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
char response = ' ';
out.print("Guessing Game - how many numbers? ");
//read in the player value
int stop = keyboard.nextInt();
GuessingGame game = new GuessingGame(stop);
game.playGame();
out.println(game);
out.println("would you like to play again? (y/n):: ");
String resp = keyboard.next();
response = resp.charAt(0);
do {
out.print("Guessing Game - how many numbers? ");
stop = keyboard.nextInt();
game.setNum(stop);
game.playGame();
out.println(game);
out.println();
out.println("would you like to play again? (y/n):: ");
resp = keyboard.next();
response = resp.charAt(0);
//
}while(response == 'y');
}
}
You have two problems here: First, your random number will always be zero. Change the line
to
Your second problem is that even if you guess right on the first try, it will always ask you twice. This stems largely from the fact that you copy and pasted your guessing code. If you instead removed these lines from your code, this would not happen (NOT the ones inside the
doloop):Further, because of the way the loop terminates, you don’t need separate
countandattemptvariables. You can always predict what theattemptvariable is going to be (one greater thancount… well, actually, in your program, it would be two greater, but that’s not the correct guessing percentage). You could remove theattemptvariable entirely, and instead do