无限循环,即使它要求输入

时间:2014-05-12 01:10:30

标签: java java.util.scanner infinite-loop

我使用扫描仪询问输入,但它只是连续打印出提示。

import java.util.Scanner;

public class Game {
    public int remaining_sticks = 0;
    public int player1_sticks = 0;
    public int player2_sticks = 0;
    public boolean player = true;
    public boolean winner = false;

    public Game(){}

    public void game(){
        //set_remaining();
    player_turn();
    check_winner();
    }
    private String switch_player(){
        if (player==true){
            this.player = false;
            return("Player 1");
        }
        else{
            this.player = true;
            return("Player 2");
        }
    }
    public void set_remaining(){
        Scanner in = new Scanner(System.in);
        System.out.println("Welcome to the game of sticks!\nHow many sticks are there on the board initially (10-100)?");
        this.remaining_sticks = Integer.parseInt(in.nextLine());
        System.out.println("\n");
        in.close();
    }
    public void check_winner(){
        if (remaining_sticks == 1 & player == true){
            this.winner = true;
            System.out.println("Player2 has won the game.");
        }
        else if (remaining_sticks == 1 & player == false){
            this.winner = true;
            System.out.println("Player1 has won the game.");
        }
    }
    public void player_turn(){
        System.out.println("There are "+Integer.toString(remaining_sticks)+" sticks on the board.\n"+switch_player()+": How many sticks do you take (1-3)?");
        if (this.player == true){
            Scanner in = new Scanner(System.in);
            if (in.hasNext()){
                String line = in.nextLine();
                player1_sticks = player1_sticks + Integer.parseInt(line);
                remaining_sticks = remaining_sticks - player1_sticks;
                System.out.println("There are "+Integer.toString(this.remaining_sticks)+" remaining.");
            }
            in.close();
        }
        else{
            Scanner in = new Scanner(System.in);
            if (in.hasNext()){
                String line = in.nextLine();
                player2_sticks = player2_sticks + Integer.parseInt(line);
                remaining_sticks = remaining_sticks - player2_sticks;
                System.out.println("There are "+Integer.toString(this.remaining_sticks)+" remaining.");
            }
            in.close();
        }
    }
}

以下是我在主类中调用它的方式:

Game game = new Game();
    game.set_remaining();
    while (game.winner == false) {
        game.game();

0 个答案:

没有答案