raymondT
raymondT

Reputation: 83

Infinite loop in rock-paper-scissors loop game

I am currently struggling to implement the while loop in my game as it always gives me an infinity loop. The idea is to continue the game except only when user types "-1"

    // declare variables
    int player, computer;
    int counter = 0;
    // player input
    System.out.println("Rock, Paper, Scissors!");
    System.out.print("Enter 0 for paper, 1 for Scissors, or 2 for Rock (-1 to quit) : ");
    player = sc.nextInt();
    while (player != -1) {

        // switch statement for player
        switch (player) {
        case 0:
            System.out.println("Player picks Paper");
            break;
        case 1:
            System.out.println("Player picks Scissors");
            break;
        case 2:
            System.out.println("Player picks Rock");
            break;
        case -1:
            System.exit(-1);
            break;
        default:
            System.out.println("Invalid input");
        }

        // generate a random number for computer
        Random randomGen = new Random();
        computer = randomGen.nextInt(3);

        // switch statement for computer
        switch (computer) {
        case 0:
            System.out.println("Computer picks Paper");
            break;
        case 1:
            System.out.println("Computer picks Scissors");
            break;
        case 2:
            System.out.println("Computer picks Rock");
            break;
        default:
        }

        // output for each condition
        if (player == 2 && computer == 1)
            System.out.println("Player Wins!");
        else if (player == 1 && computer == 0)
            System.out.println("Player Wins!");
        else if (player == 0 && computer == 2)
            System.out.println("Player Wins!");
        else if (computer == 1 && player == 0)
            System.out.println("Computer Wins!");
        else if (player == 0 && computer == 2)
            System.out.println("Computer Wins!");
        else if (player == 1 && computer == 2)
            System.out.println("Computer Wins!");
        else
            System.out.println("Draw");
        sc.close();
    }

Upvotes: 0

Views: 456

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201477

You never update your player value. Add player = sc.nextInt() to the end of the loop body. Or, do something like

int player;
while ((player = sc.nextInt()) != -1) {

And, I believe you should also remove the call to sc.close();

Upvotes: 1

Related Questions