Project 2 and Nim
Code
/// Name: Graham Pollock
/// Period: 5
/// Program Name: Nim
/// File Name: Nim.java
/// Date Finished: 02/03/2016/
import java.util.Scanner;
public class Nim
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int a, b, c, takeaway, n;
String choice, name, name1, name2;
name = "";
a = 3;
b = 4;
c = 5;
n = 0;
System.out.print("Player 1, please enter your name: ");
name1 = keyboard.next();
System.out.print("Player 2, please enter your name: ");
name2 = keyboard.next();
while (a != 0 || b !=0 || c != 0)
{
if (n % 2 == 0)
name = name1;
else
name = name2;
n++;
System.out.println("");
System.out.println("A: " + a + " B: " + b + " C: " + c);
System.out.println("");
System.out.print(name + ", choose a pile (CAPS). ");
choice = keyboard.next();
if (choice.equals("A"))
{
System.out.print("Remove how many from pile A: ");
takeaway = keyboard.nextInt();
while (takeaway > a || takeaway <= 0)
{
System.out.println("You cannot take away more than you have, or takeaway 0.");
System.out.print("How many would you like to take away? ");
takeaway = keyboard.nextInt();
}
a = a - takeaway;
}
else if (choice.equals("B"))
{
System.out.print("Remove how many from pile B: ");
takeaway = keyboard.nextInt();
while (takeaway > b || takeaway <= 0)
{
System.out.println("You cannot take away more than you have, and you must take at least 1.");
System.out.print("How many would you like to take away? ");
takeaway = keyboard.nextInt();
}
b = b - takeaway;
}
else if (choice.equals("C"))
{
System.out.print("Remove how many from pile C: ");
takeaway = keyboard.nextInt();
while (takeaway > c || takeaway <= 0)
{
System.out.println("You cannot take away more than you have, or takeaway 0.");
System.out.print("How many would you like to take away? ");
takeaway = keyboard.nextInt();
}
c = c - takeaway;
}
}
if (n % 2 == 0)
name = name1;
else
name = name2;
System.out.println(name + " you win!");
}
}
Picture of the output