これが私のコードです:
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;
}
}
ある時点で推測が num に等しくなければならないことはわかっていますが、コードは現在の「ゲーム」を終了することはありませんが、stop/upperBound に 5 の例を使用すると、無限にループしているようです
要求された私のランナークラスは次のとおりです。
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');
}
}