This my first java program. I wrote this as a Nim Game so that I could learn java while writing it. I would love to see how could this be made better.
Sample Game:
Code:
import java.util.Scanner;
public class Nim {
public static boolean isArrayZero(int[] arr){
for(int i: arr){
if(i > 0)
return false;
}
return true;
}
public static int getPile(char pile){
switch (pile) {
case 'A': return 0;
case 'B': return 1;
case 'C': return 2;
default: return -1;
}
}
public static String playerTurn(String pl1, String pl2, int nbOfTurns){
if(nbOfTurns % 2 == 0)
return pl1;
return pl2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String player1, player2, player;
int[] pile = {3,5,7};
int pileNb, howMany = 0, chosenPile = 0, nbOfTurns = 0;
char pileName;
//Get names of players
System.out.print("Player1 name: ");
player1 = input.next();
System.out.print("Player2 name: ");
player2 = input.next();
do {
System.out.println(String.format("\nA:%s\tB:%s\tC: %s", pile[0], pile[1], pile[2]) );
player = playerTurn(player1, player2, nbOfTurns);
do{
System.out.print(String.format("\n%s,Choose a pile: ", player));
pileName = Character.toUpperCase(input.next().charAt(0));
pileNb = getPile(pileName);
if(pileNb == -1)
continue;
chosenPile = pile[pileNb];
if(chosenPile == 0)
continue;
System.out.println(String.format("How many to remove from pile %s", pileName));
howMany = input.nextInt();
}while((howMany > chosenPile) || (howMany <= 0));
pile[pileNb] = chosenPile - howMany;
nbOfTurns += 1;
} while (!isArrayZero(pile));
System.out.println(String.format("%s, You loose", player) );
}
}