扫描仪行不可用错误

时间:2013-05-17 17:17:04

标签: java

我用两种不同的方法从两个不同的扫描仪对象调用Scanner.nextLine()方法。有时当我从第二种方法调用Scanner.nextLine()时,它会给我一个“ line not available ”错误。可能是什么问题?

import java.util.Scanner;

public class TicTacToe {

    private final String COMPUTER = "computer";
    private final String PLAYER = "player";

    /**
     * Asks the user to choose a letter ('X' or 'O')
     * and checks if the input is valid.
     */
    public void askLetter() {
        System.out.println("Please enter 'X' or 'O': ");
        Scanner input = new Scanner(System.in);
        String letter = input.nextLine().toUpperCase().trim();
        while (!letter.equals("X") && !letter.equals("O")) {
            System.out.println("Please enter 'X' or 'O': ");
            letter = input.nextLine().toUpperCase().trim();
        }
        input.close();
    }


    /**
     * Asks the user to choose who goes first. 
     * @return 'computer' or 'player'
     */
    public String decide() {
        //System.out.println("Choose who goes first('player' or 'computer'): ");
        Scanner input = new Scanner(System.in);
        String first = input.nextLine().toUpperCase().trim();
        while (!first.equals(COMPUTER) && !first.equals(PLAYER)) {
            System.out.println("Choose who goes first('player' or 'computer'): ");
            first = input.nextLine().toUpperCase().trim();
        }
        input.close();
        return first;
    }

    public static void main(String[] args) {
        TicTacToe tictac = new TicTacToe();
        tictac.askLetter();
        tictac.decide();
    }
}

1 个答案:

答案 0 :(得分:10)

您的askLetter方法将关闭扫描仪...将关闭System.in。然后,您尝试在System.in中重用decide

更改构造函数以接受您在Scanner中创建的main。然后将该扫描仪保留在字段中并在两种方法中使用它:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    TicTacToe tictac = new TicTacToe(scanner);
    tictac.askLetter();
    tictac.decide();
    // You might want to close the scanner here, but you don't really have to.
}

有助于使您的代码更易于测试 - 您现在可以使用由假数据支持的Scanner(例如StringReader)。