views:

60

answers:

2

here is the original code:

public static int getInt () 
{
    Scanner in = new Scanner (System.in) ; 
    if (in.hasNextInt())
    {
        int a = in.nextInt() ; 
        return a ; 
    }
    else
    {
    System.out.println ("try again:") ; 
    return getInt () ; 
    }
}

This checks and sees if the input it receives is an int. If it is then it returns the int, if not it tells you to try again and re-runs.

This is what i tried to do to change it:

public static String getIns () 
    {
        Scanner in = new Scanner (System.in) ; 
        if (in.hasNextString())
        {
            String a = in.nextString() ; 
            return a ; 
        }
        else
        {
        System.out.println ("try again:") ; 
        return getIns () ; 
        }
    }

This doesn't work though. I looked through the documentation for the scanner class and i think the problem is that there is no such method as in.hasNextString or in.nextString What methods from the scanner class can i use to do what i intend these to do?

+4  A: 

You should read the documentation.

You're looking for next and hasNext.

SLaks
+1 for faster than me.
Mark Byers
+1  A: 

Use Scanner.hasNext():

public boolean hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

matt b
i want it to make sure that token is a string though. hasNext () just verifies that something or another is there.
David
The problem is that any token it would have could be a String. You'll notice that all of the hasNextX() methods correspond to primitive types. That's because the Scanner class can tell if the next token can definitely be turned into an X. Everything can be turned into a String, so hasNext() would be the equivalent to hasNextString().
Rob Heiser