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.