我如何更改此方法以获取字符串而不是整数

发布于 2024-08-26 19:23:04 字数 841 浏览 4 评论 0原文

这是原始代码:

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 () ; 
    }
}

它检查并查看它接收到的输入是否是 int。如果是,则返回 int,如果不是,则告诉您重试并重新运行。

这就是我试图改变它的方法:

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 () ; 
        }
    }

但这不起作用。我查看了扫描仪类的文档,我认为问题是没有诸如 in.hasNextStringin.nextString 这样的方法 扫描仪类中的哪些方法可以我用来做我想做的事?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东北女汉子 2024-09-02 19:23:04

您应该阅读文档< /a>.

您正在寻找 nexthasNext

You should read the documentation.

You're looking for next and hasNext.

对风讲故事 2024-09-02 19:23:04

使用 Scanner.hasNext( )

public boolean hasNext()
如果此扫描器的输入中有另一个标记,则返回 true。此方法可能会在等待输入扫描时阻塞。扫描仪不会前进超过任何输入。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文