开发者

How do i change this method to get strings instead of ints

开发者 https://www.devze.com 2022-12-24 13:03 出处:网络
here is the original code: public static int g开发者_运维技巧etInt () { Scanner in = new Scanner (System.in) ;

here is the original code:

public static int g开发者_运维技巧etInt () 
{
    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?


You should read the documentation.

You're looking for next and hasNext.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号