简体   繁体   中英

How do I get input from the user in Java (console)?

Below I have a copy of my entire code for a tic tac toe program. I know its not much yet, but I'm stuck at the getting input part. I've managed to get 1 input from the user and then print it out (column), but then when I try to enter something different for row, it gives me whatever I was using for column. Any thoughts on how to fix it?

I'm just learning java, please be gentle.

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

    }

}

Change

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

to

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

Try input using Scanner.

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

And so on. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM