Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You should read the documentation.

You're looking for next and hasNext.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top