hasNext?

K

KyoGaSuki

What is hasNext? I know you use it when you are reading from a file
and it will stop when it has nothing more to read, but how would you
use it? I have seen a couple of different examples of it, but all
they do is make me more confused. I just can't seem to understand
it...can anyone help?
 
A

Andreas Leitgeb

KyoGaSuki said:
What is hasNext? I know you use it when you are reading from a file
and it will stop when it has nothing more to read, but how would you
use it? I have seen a couple of different examples of it, but all
they do is make me more confused. I just can't seem to understand
it...can anyone help?

e.g.:

Iterator x= ...;
while (x.hasNext()) {
... x.next() ...
}

You must make sure, that you only call ".next()" if the
previous ".hasNext()" returned true. You also shouldn't
call .next() more than once in the loop, except if you
also check again for .hasNext() .
 
S

sihle87

i think what you want is "hasNext()".
forgive me if i'm mistaken but method "hasNext()" is a boolean method
which returns either true or false, depending on the expression @
hand.
for an instance, suppose you have a string as follows:

String str="my problems are gone!";

//(say) you want to print tokens(just words of the string) you'll do
the following.

while(str.hasNext())//here you are actually asking whether is it still
true that string str has a
//token? if its true, then there is a token,
otherwise, you won't enter the loop.
{
System.out.println(str.next());
}

---------------------------the
output----------------------------------------------------------------
my
problems
are
gone!
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

sihle87
University of KwaZulu-Natal(South Africa)
Actuarial Student
-----------------------------------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top