如何从Java(控制台)获取用户的输入?

时间:2012-03-11 22:57:43

标签: java io user-input

下面我有一份关于tic tac toe程序的完整代码的副本。我知道它还不多,但我仍然坚持获得输入部分。我已经设法从用户​​那里得到1个输入然后打印出来(列),但是当我尝试输入不同的行时,它给了我用于列的任何内容。有关如何解决它的任何想法?

我只是在学习java,请保持温和。

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {

        System.out.println ("Please make your first move by entering a column and then a row, like this: c r \n");

        int columnGotten = 0;
        int rowGotten = 0;

        //gets your column number choice

        BufferedReader columnInput = new BufferedReader(new InputStreamReader (System.in));

        try {
            columnGotten = Integer.parseInt(columnInput.readLine());
        } catch (NumberFormatException nfe) {
            System.out.println ("If you're not going to play fair, I'm going to leave. Bye.");
            return;         
        }

        System.out.print ("Your column is " + columnGotten + "\n");

        //gets your row number choice

        BufferedReader rowInput = new BufferedReader(new InputStreamReader (System.in));

        try {
            rowGotten = Integer.parseInt(rowInput.readLine());
        } catch (NumberFormatException nfe) {
            System.out.println ("If you're not going to play fair, I'm going to leave. Bye.");
            return;         
        }

        System.out.print ("Your row is " + columnGotten);           

    }

}

2 个答案:

答案 0 :(得分:4)

更改

System.out.print ("Your row is " + columnGotten);

System.out.print ("Your row is " + rowGotten);

答案 1 :(得分:2)

使用扫描仪尝试输入。

Scanner sc = new Scanner();
int x = sc.nextInt();
String s = sc.nextLine();

等等。希望它有所帮助。