当要求用户输入char时,为什么会收到错误消息?

时间:2018-05-08 18:26:45

标签: java

private static Scanner keyboard = new Scanner(System.in);
private static char[] board = new char[9];
private static boolean[] isAvail = new boolean[9];
private static char currentPlayer = ' ';
private static char playAgain = ' ';

// *******************************************************
public static void main(String[] args) {

    System.out.println("Welcome to Tic-Tac-Toe!!");
    System.out.print("Would you like to play a game? (enter 'y' for yes or 'n' for no): ");

    do {
    char play = ' ';
    for(int i = 0; i < 9; i++)
        isAvail[i] = false;

    play = keyboard.nextLine().charAt(0); 

    System.out.println();

    if (play != 'y') {
        System.out.println("Goodbye!");
        System.exit(0);
    }

    playGame();

    playAgain = ' ';
    System.out.print("Would you like to play another game (enter 'y' for yes or 'n' for no): ");
    //String space = keyboard.nextLine();
    playAgain = keyboard.nextLine().charAt(0); 


    }while(playAgain == 'y');

    System.out.println("Goodbye!");

}

我正在用很多方法做一个tic-tac-toe程序。在该方法中,存在do-while循环,其询问用户他们是否想要玩游戏然后在游戏完成之后他们是否想要再次玩游戏。当我取出String space = keyboard.nextLine();我收到一条错误信息,但是当我在用户输入时必须输入两次才能再次播放。如何解决这个问题只能输入y再次播放?感谢

示例:

Would you like to play another game (enter 'y' for yes or 'n' for no): 
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at TicTacToeMihalovich.main(TicTacToeMihalovich.java:37)

1 个答案:

答案 0 :(得分:0)

只需删除char play = ' ';,然后继续playAgain

System.out.println("Welcome to Tic-Tac-Toe!!");
System.out.print("Would you like to play a game? (enter 'y' for yes or 'n' for no): ");



do {
    playAgain = keyboard.nextLine().charAt(0);


    for(int i = 0; i < 9; i++)
        isAvail[i] = false;


    System.out.println();

    if (playAgain != 'y') {
        System.out.println("Goodbye!");
        System.exit(0);
    }

    playGame();



    //playAgain = ' ';
    System.out.print("Would you like to play another game (enter 'y' for yes or 'n' for no): ");
    //String space = keyboard.nextLine();
    //playAgain = keyboard.nextLine().charAt(0);


} while(playAgain == 'y');

System.out.println("Goodbye!");

}