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!

