Project 2
Code
/// Name: Xinting Chen
/// Period: 7
/// Program Name: Project 2
/// File Name: Project2.java
/// Date Finished: 3/1/2016
import java.util.Scanner;
import java.util.Random;
public class Project2
{
public static void main(String[] args)
{
Random r = new Random();
Scanner keyboard = new Scanner(System.in);
int pile0, pile1, pile2, pile3;
String player1, player2;
byte Player, Pile = 0;
String read = " ";
boolean correct = false;
int remove = 0;
pile0 = r.nextInt(7) + 1;
pile1 = pile0 +1;
pile2 = pile1 +1;
System.out.println("Welcome to the NIM game!\n");
Player = 1;
System.out.print("Player 1, enter your name: ");
player1 = keyboard.next();
System.out.println();
System.out.print("Player 2: ");
player1 = keyboard.next();
System.out.println();
while (pile0+ pile1+ pile2!=0)
{
System.out.println("A: "+pile0+" B: "+pile1+" C: "+pile2+"\n");
correct = false;
do
{
System.out.print( Player + ", choose a pile: ");
read = keyboard.next();
correct = true;
switch (read)
{
case "A": Pile = 0;
break;
case "B": Pile = 1;
break;
case "C": Pile = 2;
break;
default: correct = false;
System.out.println("Choose A, B or C");
break;
}
if (Pile ==0 && correct)
{
System.out.println("The chosen pile is empty, choose another one!");
correct = false;
}
}
while (!correct);
do
{
System.out.print("How many to remove from that pile? ");
remove = keyboard.nextInt();
correct = true;
if (remove<=0)
{
System.out.println("You have to enter a positive number!!!");
correct = false;
}
if (Pile < remove && correct)
{
System.out.println("You entered too many! The max you can remove is "+ Pile);
correct = false;
}
if (correct) Pile -= remove;
}
while (!correct);
if (Player==0) Player = 1;
else Player = 0;
}
System.out.println("You won, "+ Player +"!");
if (Player==0) Player = 1;
else Player = 0;
System.out.println("You lose, "+ Player +"!");
System.out.println();
}
}
Picture of the output