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?
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 usescanner.nextLine()?String itemInfo = "4 6";The problem is from yourscannerhas shown by @Aaron.Scanner#nextLine()to read the whole line and then split the tokens, or read each token vianext()like you do, then there is no need to split by space.