使用扫描仪读取int和char输入?

时间:2017-04-26 19:48:23

标签: java

好的大家好。我正在尝试为奥赛罗游戏开发代码。我遇到了一个需要帮助的问题。我想知道如何在一个扫描仪中输入int和char。例如,如果用户为列输入D,为行输入6,则它看起来像这样

enter image description here

我想要的是当用户输入D6而不是单独询问列和行时,能够用新点绘制电路板,我希望它能一次性完成扫描输入。我已经浏览了整个网络,但无法得出结论。这是我需要帮助的代码

public static void main (String args[]){
    char column;
    int row;
    Scanner scan = new Scanner(System.in);
    Othello game = new Othello();
    //game.startGame();
    game.displayBoard();
    do{
        do{
            System.out.print("Enter the column: ");     //get column from user
            column = scan.next().charAt(0);
        }while (game.checkColumn(column) == false);     //loop until input is valid 


        do{
            System.out.print("Enter the row   : ");     //get row from user
            row = scan.nextInt();
        }while (game.checkRow(row) == false);           //loop until input is valid 

        game.takeTurn(game, column, row);
    }while (1==1);

2 个答案:

答案 0 :(得分:2)

我建议你阅读整行,然后解析你需要的东西。

注意:此解决方案仅适用于单个字符/数字组合。如果您想要更复杂的东西,请使用正则表达式。

public static void main (String args[]){
    char column;
    int row;
    Scanner scan = new Scanner(System.in);
    Othello game = new Othello();
    //game.startGame();

    while (true) {

        game.displayBoard();

        do {
            System.out.print("Enter the column, then row, for example (A0): "); 
            String line = scan.nextLine();
            column = line.charAt(0);
            row = Integer.parseInt("" + line.charAt(1));
        } while (!( game.checkColumn(column) && game.checkRow(row) );     //loop until input is valid 

        game.takeTurn(column, row); // Remove game as a parameter here. It is not needed

        // if (gameOver) break; 
    }
}

答案 1 :(得分:0)

值得注意的是Scanner会将空格分隔的输入读作一系列值,因此,如果用户键入&#34; D 6&#34;:< / p>

System.out.println("Enter ROW COL: ");
char column = scan.next().charAt(0);
int row = scan.nextInt();
scan.nextLine(); // clear new line

另一方面,如果您想阅读&#34; D6&#34;,那么您需要将输入作为字符串读取,并手动从中提取组件:

System.out.println("Enter ROWCOL: ");
String raw = scan.next();
char column = raw.charAt(0);
int row = Character.getNumericValue(raw.charAt(1)); //get 2nd digit as int
scan.nextLine(); // clear new line