Having trouble with scanner.hasNext()

hey guys,

i'm doing in assignment for which i need to use the scanner class's hasNext() method but for some reasons i'm not getting teh result i expect maybe someone could help me and explain me where my understanding is wrong, thanks i advance

here's what i've, very simpleand basic code:

publicstaticvoid main (String[] args)

{

String str ="My name is" +"\n" +"Muhammad";

Scanner input =new Scanner(System.in);

while (input.hasNext ()){

System.out.println (input.next ());

System.out.println(input.hasNext ());

}

}

If my input isthis:"My name" then it should display:

My

true

name

false

and then exit from the loop but it's not doing that instead it displays this:

my

true

name and then asksfor input again, then displays

true (that's obvious bec, i feed another input)

However, if i've pass a string as an paramter to scanner then it works fine. e.g.

String str ="My name is" +"\n" +"Muhammad";

Scanner input =new Scanner(str);

Output:

My

true

name

true

is

true

Muhammad

false

Could someone please explain me what is the problem or where my understanding is wrong, thanks in advance!

[2184 byte] By [salubadshaa] at [2007-10-3 5:20:32]
# 1
A String has a known length, so Scanner can tell when it has reached the end.System.in, on the other hand, is attached to an input device. How should it know that you are done inputting stuff?
warnerjaa at 2007-7-14 23:27:27 > top of Java-index,Java Essentials,Java Programming...
# 2

ok i got that but is there way to get out of the loop? Because what i'm eventually trying to do is read an input, could be mutliple lines, then do some manipulation. The only problem is that, i've line which asks for an input so if there're multiple lines input then that line is excuted but since multiple lines,

myscanner.nextLine() will not ask for another input. So, i want somehow to stop that line to be excuted if there're still tokens.

salubadshaa at 2007-7-14 23:27:27 > top of Java-index,Java Essentials,Java Programming...
# 3

> ok i got that but is there way to get out of the

> loop? Because what i'm eventually trying to do is

> read an input, could be mutliple lines, then do some

> manipulation.

If you're reading from the keyboard--i.e., System.in--how will you, the user, signal to your program that you're done?

* Not type anything for 30 seconds? Ick.

* Type a special "DONE" token?

* Enter a fixed number of lines?

There has to be some agreed upon signal between your program and whoever/whatever is providing the input as to what it means to be "done." Decide on that, and write your code accordingly.

There's no way to know that there are "no more tokens" on System.in, because System.in doesn't "end."

jverda at 2007-7-14 23:27:27 > top of Java-index,Java Essentials,Java Programming...