0

I am trying to ask the user for two ints separated by a space. I also want to store the two separated numbers into two integer variables. Please help it is so simple I am having a hard time finding a good source for it.

System.out.print("Please enter 2 integers (separated by spaces): ");
            String numbers = kb.nextLine();
            kb.useDelimiter(" ");
NHJP
  • 1

2 Answers2

1

You can declare the Scanner to use the regex delimiter of \\s+ which will remove all whitespace, or \\s if you want to remove a single space, but throw an Exception for any other input (such as two spaces in a row).

Additionally, ensure you call this method before you attempt to use kb.next():

Scanner kb = new Scanner(System.in);
kb.useDelimiter("\\s+");
System.out.print("Please enter 2 integers (separated by spaces): ");
int valueOne = kb.nextInt();
int valueTwo = kb.nextInt();
System.out.println("Output: " + valueOne + " " + valueTwo);

You then individually can grab each input using kb.nextInt(), calling it as many times as you need, depending on how many values you want.

I suggest if you need a lot of values you instead call this from a loop, and not keep rewriting it.

Trial Run:

Please enter 2 integers (separated by spaces): 5 6

Output: 5 6

Note that this will only take in integers and throw an InputMismatchException if you attempt to use anything else. You use kb.next() instead which will read a String if you want any value, then parse it into the type you need.

Community
  • 1
  • 1
Nexevis
  • 4,647
  • 3
  • 13
  • 22
0

In place of useDelimiter, since you've already read the line, you could split on space and convert each of those values to ints:

System.out.print("Please enter 2 integers (separated by spaces): ");
Scanner kb = new Scanner(System.in);
String numbers = kb.nextLine();
String[] values = numbers.split(" ");
for(String value: values)
{
    System.out.println(Integer.parseInt(value));
}

Bear in mind that this will raise exceptions if non-numbers are provided as inputs.

Anoop R Desai
  • 712
  • 5
  • 18
  • Note that this will not read _two_ values, but every value on the line. Entering `2 3 4 5 6` will give results for all 5 values which is not exactly the same thing. – Nexevis Sep 19 '19 at 19:57