我正试图在学校制作一个nim游戏,不幸的是我得到了与我想要的输出不同的输出;这是我的代码。
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块石头
答案 0 :(得分:0)
有很多问题:
numStonesLeft
。numStonesLeft -= stonesChosen;
。numStonesLeft >= 0
。if
之后放置分号可能会以无条件执行以下范围的方式进行解析。停止在行的开头放置随机分号。stonesChosen = input.nextInt();
。