我正在尝试在学校制作尼姆游戏,不幸的是,我的输出与所需的输出不同。这是我的代码。
import java.util.Random;
import java.util.Scanner;
public class Nim2 {
private static int numStonesLeft;
/**
*/
/**
* The computerTurn method chooses a random number from 1 to 3 if
* numStonesLeft is greater than or equal to 3, otherwise chooses a random
* number from 1 to numStonesLeft.
*
* Then decrements numStonesLeft appropriately and prints the turn.
*/
public static void computerTurn() {
int stonesChosen = (int) (Math.random() * 16) + 15;
numStonesLeft -= stonesChosen;
System.out.println("nI took " + stonesChosen + " stones.");
System.out.println("There are " + numStonesLeft + " stones left.");
}
/**
* The playerTurn method prompts the user for a valid number of stones to
* choose and reads an int value from the user and will repeat this action
* while the user input is invalid. (i.e. user must choose 1, 2 or 3 AND
* their choice must be less than or equal to numStonesLeft.)
*
* Also decrements numStonesLeft appropriately and prints the turn.
*/
public static void playerTurn() {
Scanner input = new Scanner(System.in);
System.out.println("Number of stones you take this turn:");
int stonesChosen = 0;
stonesChosen = input.nextInt();
while (stonesChosen > 3 || stonesChosen < 1) {
;
System.out.println("That is an invalid number of stones.");
stonesChosen = input.nextInt();
}
if (stonesChosen <= 3 || stonesChosen >= 1)
;
{
System.out.println("nYou took " + stonesChosen + " stones.");
System.out.println("There are " + (numStonesLeft - stonesChosen)
+ " stones left.");
}
stonesChosen = input.nextInt();
}
public void gameEnded() {
boolean over = false;
}
}
不同的客户端代码
public class TestNim2 {
public static void main(String[] args) {
Nim2 nim = new Nim2();
int numStonesLeft = (int) (Math.random() * 16) + 15;
System.out.println("This is the Game of nim.");
System.out.println("There is a pile of " + numStonesLeft
+ " stones between us.");
System.out.println("We alternate taking either 1,2 or 3 stones.");
System.out.println("The person who takes the last stone loses");
// Write a loop to alternate computerTurn() and playerTurn()
// checking after each turn see if there is a winner to print
// and to break the loop ... then output the winner
nim.playerTurn();
nim.computerTurn();
}
}
我获得的输出是
您以此回合的石头数:2
你拿了2块石头。还有-2个石头。3
我拿了16块石头。剩下-16石头。
我所需的输出应该类似于这样的东西
你拿了2块石头。有18个石头左//随机数20
我拿了3块石头,有15块石头
有很多问题:
- 您不初始化
numStonesLeft
。 - 您忘记了播放器转弯中的
numStonesLeft -= stonesChosen;
。 - 扣除后没有检查
numStonesLeft >= 0
。 - 在
if
之后放置半隆的方式可能以无条件执行以下范围的方式解析。停止将随机分号放在线的开头。 - 播放器转弯的多余
stonesChosen = input.nextInt();
。