Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: Get 2 values for integer variables from the user in 1 line?

I'm trying to figure out if there is a way for the user to enter two values on one line and put each value in a separate variable.

For example, I have an integer variable "x" and an integer variable "y". I prompt the user saying: "Enter the x and y coordinates: ". Lets say the user types: "1 4". How can I scan x=1 and y=4?

like image 789
Petefic Avatar asked Oct 28 '25 22:10

Petefic


2 Answers

    Scanner scn = new Scanner(System.in);
    int x = scn.nextInt();
    int y = scn.nextInt();
like image 163
msi Avatar answered Oct 30 '25 14:10

msi


You could do it something like this:

public class ReadString {

   public static void main (String[] args) {


      System.out.print("Enter to values: x y");

      //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String values = null;


      try {
         values = br.readLine();
        String[] split = values.split(" ");
        if(split.length == 2)
        {
            int x = Integer.parseInt(split[0]);
            int y = Integer.parseInt(split[1]);
        }else{
            //TODO handle error
        }

      } catch (IOException ioe) {
         System.out.println("IO error!");
         System.exit(1);
      }



   }

}  
like image 31
Daniel Kurka Avatar answered Oct 30 '25 14:10

Daniel Kurka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!