
Java
- Starts with 21 matchsticks
- each player must remove 1 - 4 matchsticks
- The player who takes the last stick loses.
The algorithm is this: To always win you must:
- Let your opponent go first.
- on your turn, take enough sticks that your take plus your opponent's take equal 5 sticks.
This program is written in Java, and uses the above algorithm:
import Java.io.InputStreamReader; import Java.io.BufferedReader; import Java.io.InputStream; public class Matchstick { static int sticksLeft = 21; public static void main(String[] args) { String input; int humanChoice; int computerChoice; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Welcome To Matchsticks\n\n" + "The Rules:\n" + " - There are 21 Matchsticks\n" + " - Each player takes 1, 2, 3, or 4 matchsticks on their turn\n" + " - The person who takes the last matchstick loses the game\n\n" + "The computer has graciously let you pick first"); do { try { System.out.print("How many sticks do you take: "); System.out.flush(); input = in.readLine(); humanChoice = Integer.parseInt(input); if (humanChoice > 4 humanChoice < 1) { System.out.println("Please choose a number between 1 and 4\n"); } else { sticksLeft = sticksLeft - humanChoice; System.out.println("You chose to remove " + humanChoice + " Matchsticks. There are " + sticksLeft + " Matchsticks Left"); computerChoice = 5 - humanChoice; sticksLeft = sticksLeft - computerChoice; System.out.println("I chose to remove " + computerChoice + " Matchsticks. There's " + sticksLeft + " Matchstick(s) Left\n"); } } catch (Exception e) { System.out.println("Please enter a numeric value\n"); } } while (sticksLeft != 1); System.out.println("You take the last Matchstick, The computer wins!"); System.exit(0); } }
Copyright © 2026 eLLeNow.com All Rights Reserved.