Hello,
I am working on a method that will count the number of tokens in a string, specifically integers. However, i'm finding that for some reason it is running endlessly even though there are only a small amount of tokens in the given string. I have a feeling given the small amount of code it is a conceptual misunderstanding somewhere on my part. Below is the method in question, any direction would be appreciated!
public static void countNumbers(String numstring)
{
int numbers = 0;
Scanner input = new Scanner(numstring);
while ( input.hasNext() )
{
numbers++;
System.out.println(numbers);
}
}
Comments
you're right, input.hasNext() does not "consume" any data thus the first integer will cause an infinite loop.
[link=http://java.sun.com/javase/6/docs/api/java/util/Scanner.html]scanner class[/link] has methods to "consume" data and advance the "pointer" (those methods mostly begin with [italic]nextXXX()[/italic].