这是我的代码:
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;
}
}
我知道它必须在某些时候guess 必须等于 num 但代码永远不会结束当前的“游戏”但是当我使用我的示例 5 作为 stop/upperBound 时它似乎是无限循环的
这是我要求的跑步者课程:
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');
}
}