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

30,246

Solution 1

    Scanner scn = new Scanner(System.in);
    int x = scn.nextInt();
    int y = scn.nextInt();

Solution 2

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



   }

}  

Solution 3

int[] arr = new int[2];
for (int i = 0; i < arr.length; ++i){
    try{
        int num = Integer.parseInt(in.next()); // casting the input(making it integer)
        arr[i] = num;
    } catch(NumberFormatException e) { }
}

Solution 4

String[] temp;    
String delimiter = "-";
      /* given string will be split by the argument delimiter provided. */
      temp = str.split(delimiter);
      /* print substrings */
      for(int i =0; i < temp.length ; i++)
        System.out.println(temp[i]);
Share:
30,246
Petefic
Author by

Petefic

Updated on July 09, 2022

Comments

  • Petefic
    Petefic almost 2 years

    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?

    • Dave Newton
      Dave Newton over 12 years
      Split on space and parse the array elements.
  • Dave Newton
    Dave Newton over 12 years
    Or use a Scanner.
  • msi
    msi over 12 years
    Scanner is better as it gives you a far clearer code. No need for parsing and dealing with arrays.
  • Dave Newton
    Dave Newton over 12 years
    Not really "far" cleaner, but incrementally cleaner.
  • Petefic
    Petefic over 12 years
    Thank you, I didn't realize it was this simple!