Skip to content

How to parse (via loop) through a string until the end of the string?

Given String “5 6 7 8 9 2 3 ” how do you use a while loop or for loop to cycle through each number without repeating the string (as a while loop would)?

 String myString = "5 6 7 8 9 2 3";

Scanner myScanner = new Scanner(myString);
while(myScanner.hasNext())
{
//do something
}

I can’t get the loop the stop. It keeps repeating the same string pattern over and over and over.

Answer

So far your code asks whether the scanner has more items. But you never consume them. So inside your loop you need to call something like

String currentItem = myScanner.next();