Click to See Complete Forum and Search --> : System.out.println() not working after while(hasNext()) for scanner


sugarbabee
09-30-2008, 05:28 PM
Hi there, I'm currently trying to get this code to work so that each word of a user's input will be stored in an array, which I do using a while(scanner.hasNext()) loop, and then I want to be able to loop through the resulting array and print output its contents using system.out.println(). The problem is that nothing seems to happen once the loop has finished, even if I try to print some random message like "adadfh" after, it doesn't output.

Does anyone know why this is happening? Here is the loop:


String[] array = new String[10];
counter = 0;
Scanner s = new Scanner(System.in);
while(s.hasNext()) {
String i = s.next();
array[counter] = i;
counter ++;
}


System.out.println("This won't print");


Any help would be greatly appreciated, maybe its something in the Scanner that's preventing the code after it from executing?

Thanks in advance!

FourCourtJester
09-30-2008, 05:37 PM
Hi there,

Just my theory, but first, your Scanner is using the System.in stream, which probably blocks all subsequent System calls.

Second, you don't close the Scanner (s.close() after the loop), thus also probably blocking the System.out call.

Try either closing the stream after the loop, or read in your text to a string or file and open that instead of the System.in stream.

sugarbabee
09-30-2008, 05:56 PM
thanks for the response!

I did actually have s.close in there after the loop, I just forgot to post it in the message...and it doesn't fix the problem.

As for reading the text to a string or file...how would I do this? And I'm supposed to use System.in so that the user can input the string, or is there another option?

Thanks for your help :)

chazzy
09-30-2008, 06:17 PM
while(s.hasNext()) {
String i = s.next();
array[counter] = i;
counter ++;
}

s.hasNext() will always return true for System.in. You need to add something in that's supposed to be the end of the input, maybe something like this


while(s.hasNext()) {
String i = s.next();
array[counter] = i;
counter ++;
if(i.equalsIgnoreCase("exit"))
break;
}

sugarbabee
09-30-2008, 06:38 PM
Okay, I'm going to try to get the input and save it to a string, close the scanner and then loop through the string storing in an array as I hit spaces...good theory in my head, hopefully its doable, I'll post again if I run into trouble with it.

Thanks for the help!