Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

Explain the nim game Java.

Asked by Alison Kelly Oct 6, 2022 521 views 1 answer
Share

About this question

 it's a game where you enter a number between 1 and 3, This number is than removed from 12, in doing so the computer will then pick a number between 1-3 based on what number you have picked, if you choose to remove 1 marble it should say that it has removed 3 marbles. This works because there are 3 lots of 4 in 12. And the maths tells it to remove what number you have chosen from 4. Because there are 3 lots of 4, you can never win, which is the whole point of the game.


Is there any way I could improve on the code?


 import java.util.Scanner;
    public class Main {
        public static int input;
        public static int marble = 12;
        public static int comFirst = (int) (Math.random() * 3 + 1);
        @SuppressWarnings("resource")
        public static void main(String[] args) throws InterruptedException {
            System.out.println("There Are 12 Marbles, You Can Only Remove Up To 3 Marbles At A Time");
            System.out.println("Your Goal Is To Remove The Last Marble, Marble 1");
            System.out.println("To Remove A Marble Either Enter 1, 2 or 3");
            System.out.println("");
            while (true) {
                if (marble == 1) {
                    System.out.println("There Is " + marble + " Marble Remaining");
                } else {
                    System.out.println("There Are " + marble + " Marbles Remaining");
                }
                Scanner scanInput = new Scanner(System.in);
                input = scanInput.nextInt();
                if (input > 3 || input < 1>                    System.out.println("You Can Only Remove 3 Marbles At A Time");
                } else {
                    marble = marble - input;
                    Thread.sleep(250);
                    int cpuAnswer = 4 - input;
                    if (cpuAnswer == 1) {
                        System.out.println("The Computer Has Removed " + cpuAnswer + " Marble");
                    } else {
                        System.out.println("The Computer Has Removed " + cpuAnswer + " Marbles");
                    }
                    if (marble - cpuAnswer == 0) {
                        System.out.println("There Are No Marbles Remaining, The Computer Has Won!!");
                        System.out.println("The Computer Has Won");
                        return;
                    }
                    if (marble - input == 0) {
                        System.out.println("There Are No Marbles Remaining, You Have Won!!");
                        return;
                    }
                    marble = marble - cpuAnswer;
                }
            }
        }
    }

Your answer

1 Answer

More Java discussions