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

Java 无限循环,即使它要求输入,java,java.util.scanner,infinite-loop,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;

我使用扫描仪来请求输入,但它只是连续打印出提示

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();

您应该遵循Java命名约定,即
lowerCamelCase
。此外,请更好地命名您的方法。
game()
做什么?应将其重命名为
tick()
turn()
。您所指的“提示”是什么?请说明以缩小问题范围。您正在实例化扫描仪,而没有告诉编译器等待输入…因此程序执行会不断循环…-->int line=in.nextInt();