编辑 1 - 我将所有 sc.nextInt 更改为 Integer.parseInt(sc.nextLine()) 我现在有一些错误但更少
编辑 2 - 它现在运行,但我的东西打印了 2x,游戏在第 10 轮结束时没有结束,我在最后错过了总胜线。我认为错误发生在获胜后。
编辑 3 - 2x 冷/热打印已修复。修复了 2x 标头(wins 方法中的重复行)。新的(希望是最后一个错误)- 第一轮游戏只允许 3 次尝试,其他轮 4 次。示例运行:
I will choose a number between 1 and 10
You have 3 tries to get it right
Round 1
Enter a new guess: 5
Cold
5
Cold
5
You lose!
You have won 0 out of 1 rounds.
Round 2
Enter a new guess: 5
Cold
5
Cold
5
Cold
5
You lose!
You have won 0 out of 2 rounds.
Round 3
Enter a new guess: 5
Cold
5
Cold
5
Cold
5
You lose!
You have won 0 out of 3 rounds.
第一类:
import java.util.Scanner;
public class GuessRunner
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("I will choose a number between 1 and 10" +
'\n' + "You have 3 tries to get it right" + '\n');
GuessCalc game = new GuessCalc();
while (game.getRounds() <= 10)
{
System.out.println('\n' + "Round " + game.getRounds() + '\n');
System.out.print("Enter a new guess: ");
int guess = Integer.parseInt(sc.nextLine());
do
{
game.rounds(guess);
guess = Integer.parseInt(sc.nextLine());
}
while (game.roundOver == false);
System.out.println(game.wins());
}
sc.close();
}
}
第 2 类:
public class GuessCalc
{
private int wins;
private int rounds = 1;
private int num = (int) (1 + Math.random() * 10);
private int tries = 0;
public boolean roundOver;
/**
* Runs the rounds and determines if they win
* @return outcome the boolean true if they won or false if they lost
*/
public String rounds(int guess)
{
if (guess == num) //player won
{
wins++;
rounds++;
tries = 0;
System.out.println("You win!");
num = (int) (1 + Math.random() * 10); //new number
roundOver = true;
}
else if (tries == 3) //out of tries
{
rounds++;
tries = 0;
System.out.println("You lose!");
num = (int) (1 + Math.random() * 10); //new number
roundOver = true;
}
else
{
hotOrCold(guess);
roundOver = false;
}
}
/**
* Tells the player if they are hot or cold
*/
public void hotOrCold(int guess)
{
if (guess == num - 1 || guess == num + 1) //if they are off by 1
System.out.println("Hot");
else // if they are further than 1 away
System.out.println("Cold");
tries++;
}
/**
* Returns the number of wins and makes a new header
* @return the String with the number of wins and new header
*/
public String wins()
{return("You have won " + wins + " out of " + (rounds - 1) + " rounds.");}
/**
* Returns the number of rounds played
* @return rounds the number of rounds
*/
public int getRounds()
{return rounds;}
}