首页 > 解决方案 > 为什么在要求用户输入字符时收到错误消息?

问题描述

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!");

}

我正在用很多方法做一个井字游戏。在这种方法中,有一个 do-while 循环询问用户是否想玩游戏,然后在游戏完成后他们是否想再玩一次。当我取出字符串空间 = keyboard.nextLine(); 行我收到一条错误消息,但是当我有它时,用户必须输入 y 两次才能再次播放。我该如何解决这个问题,只输入一次 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)

标签: java

解决方案


只需删除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!");

}

推荐阅读