0
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();

I got the beginning started but I'm stuck at the part where the user is only suppose to take 1,2, or 3 stones from the pile. I tried doing do,while,for,if,else and none of those loops are doing what I want it to do because the user is only suppose to have one turn then its the computers turn to pick up to 3 stones out of the pile.

2 Answers2

1

Here you are taking the input from user

 System.out.println("How many stones would you like to remove? ");
 user = input.nextInt();

After taking the input, just compare the value and if it is in between 1 and 3 then prompt correct and if it is not in between 1 and 3, then just display a message saying "Input should be in between 1 and 3".

if(user >0 && user <= 3) {
  //do the needful
} else {
  //Print the custom message saying that wrong input
}
Kamal Chanda
  • 163
  • 2
  • 12
  • what if the user inputs more than 2 wrong numbers because it doesn't loop back around @Kamal Chanda – Courtney Oct 10 '17 at 18:07
  • Hey you can try adding like this `boolean check = true; while(check) { System.out.println("How many stones would you like to remove? "); user = input.nextInt(); if(user > 0 && user <= 3) { check = false; } else { System.out.println("Invalid input please enter again"); check = true; } }` – Kamal Chanda Oct 10 '17 at 18:28
0

add this after 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;
 }

This will test if the user has entered the correct input and prompt them to enter it until a value between 1 and 3 has been entered.