4

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?

1
  • Split on space and parse the array elements. Commented Jan 29, 2012 at 21:08

5 Answers 5

9
    Scanner scn = new Scanner(System.in);
    int x = scn.nextInt();
    int y = scn.nextInt();
Sign up to request clarification or add additional context in comments.

4 Comments

Or use a Scanner.
Scanner is better as it gives you a far clearer code. No need for parsing and dealing with arrays.
Not really "far" cleaner, but incrementally cleaner.
Thank you, I didn't realize it was this simple!
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);
      }



   }

}  

Comments

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

Comments

1
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) { }
}

Comments

0

input is your input of type String

String[] values = input.split(" ");
x = Integer.valueOf(values[0]);
y = Integer.valueOf(values[1]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.