0

I've a simple code:

System.out.println("Enter ItemID ~SPACE~ Quantity: ");
String itemInfo = scanner.next();

String[] selectedItem = itemInfo.split("\\s+",2);

System.out.println(selectedItem.length);
System.out.println("The item selected for order is: " + selectedItem[0] + " and the quantity is: " + selectedItem[1]);

Let's say user enters 4 6 then the print statements prints 1 and then an error about Exception in thread "main" java.lang which basically means selectedItem[1] does not exist or is null.

My question is how do I split the string so that when user enters 4 6 it give me 4 and 6 on indexes 0 and 1?

3
  • 6
    Using scanner.next() already "splits" around spaces. Scanner.next() only reads the next token, where tokens are separated by the scanner's separator which by default includes spaces. Maybe you wanted to use scanner.nextLine() ? Commented Sep 8, 2021 at 12:03
  • Your code is fine with String itemInfo = "4 6"; The problem is from your scanner has shown by @Aaron. Commented Sep 8, 2021 at 12:03
  • 1
    Either use Scanner#nextLine() to read the whole line and then split the tokens, or read each token via next() like you do, then there is no need to split by space. Commented Sep 8, 2021 at 12:04

1 Answer 1

1

you have to just change scanner.next() to scanner.nextLine() and it will be done.

Sign up to request clarification or add additional context in comments.

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.