import java.util.Random;
import java.io.*;
import java.util.*;
/**
Courtney Fox
Professor Yao
Midterm Part 1
10/10/17
Purpose:
The purpose of this program is to develop a Nim game that consists of a
pile of stones ranging from 10-16. From that pile, both the player and
computer have to pick up to 3 stones and whoever gets the last stone
loses.
Logic:
**/
public class FoxMidQ1
{
public static void main(String[] args)
{
//Variables
int user = 0;
//int computer;
//int loser;
int gamenum = 0;
//Scanner
Scanner input = new Scanner(System.in);
//Welcome Output
System.out.println("Welcome to Nim Game!");
//Get pile size: Randomly generate 10-16
int[] pile = {10, 11, 12, 13, 14, 15 , 16};
int stones = pile[(int)(Math.random() * pile.length)];
System.out.println("Game #"+ (gamenum + 1) +": There are "+ stones + "
stones in the pile.");
System.out.println("You can remove up to 3 stones from pile at a
time.");
//User takes stones
System.out.println("How many stones would you like to remove? ");
user = input.nextInt();
我开始了,但我被困在用户只应该从堆中取出 1、2 或 3 块石头的部分。我尝试做 do,while,for,if,else,这些循环都没有做我想让它做的事情,因为用户只假设有一个回合,然后是计算机轮到从堆中捡起最多 3 块石头。
在这里,您正在从用户那里获取输入
System.out.println("How many stones would you like to remove? ");
user = input.nextInt();
输入后,只需比较值,如果它在 1 和 3 之间,则提示更正,如果它不在 1 和 3 之间,则只需显示一条消息,说"输入应该在 1 和 3 之间"。
if(user >0 && user <= 3) {
//do the needful
} else {
//Print the custom message saying that wrong input
}
在user = input.nextInt();
之后添加这个
boolean testForCorrectInput = true;
while(testForCorrectInput)
{
if(user < 1 || user >3)
{
System.out.println("nWrong input. Please enter a number between 1 and 3");
user = input.nextInt();
}
else
testForCorrectInput = false;
}
这将测试用户是否输入了正确的输入,并提示他们输入该输入,直到输入了介于 1 和 3 之间的值。