在if条件JAVA中从sc.nextLine()获取输入的问题

发布于 2025-01-10 14:52:24 字数 483 浏览 4 评论 0原文

[[图像描述]]

    System.out.print("Enter the key: ");
    int n=sc.nextInt();

    if(n==1)
    {
        System.out.println("Enter the task:");
        String k=sc.nextLine();
        System.out.println(k);
    }

输入密钥:正在打印,给出 n=1 后,它只是打印 输入任务:,整个程序终止。但是,当我给 sc.next() 它工作,但我的输入有多个单词时,sc.nextLine() 是否有任何问题。

[[Image description ]]

    System.out.print("Enter the key: ");
    int n=sc.nextInt();

    if(n==1)
    {
        System.out.println("Enter the task:");
        String k=sc.nextLine();
        System.out.println(k);
    }

Enter the key: is printing, after giving n=1, it just print
Enter the task: and the whole program is terminated. But when I give sc.next() it working but my input has more than one word, is there any problem in sc.nextLine().

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

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

发布评论

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

评论(3

离线来电— 2025-01-17 14:52:24

在这种情况下,每当编写scanner.nextInt()时,该方法都不会返回换行符或不接受用户的任何输入。因此,如果您想要完美的输出,那么您需要在从用户获取字符串值之前放置scanner.next()。之后你可以使用scanner.nextLine(),它会正常工作。

Whenever write scanner.nextInt() in that case this method doesn't return new line character or don't accept any input from user. So if you want perfect output then you need to put scanner.next() before getting string value from user. After that you can use scanner.nextLine() and it will be work fine.

提笔落墨 2025-01-17 14:52:24

这是一个常见的概念问题。阅读这三个函数的java文档。同时你可以尝试下面的代码。它会起作用的。

System.out.print("Enter the key: ");
int n=sc.nextInt();
sc.nextLine();

if(n==1)
{
    System.out.println("Enter the task:");
    String k=sc.nextLine();
    System.out.println(k);
}

This is a common conceptual problem. Read the java docs of these three functions. Meanwhile you can try the following code. It'll work.

System.out.print("Enter the key: ");
int n=sc.nextInt();
sc.nextLine();

if(n==1)
{
    System.out.println("Enter the task:");
    String k=sc.nextLine();
    System.out.println(k);
}
流殇 2025-01-17 14:52:24

那是因为Scanner.nextInt方法没有读取换行符
通过按“Enter”创建输入中的字符,因此调用
Scanner.nextLine 在读取换行符后返回。

当您使用Scanner.nextLine时,您会遇到类似的行为
在 Scanner.next() 或任何 Scanner.nextFoo 方法之后(除了 nextLine
本身)。

答案和解决方法位于此处

That's because the Scanner.nextInt method does not read the newline
character in your input created by hitting "Enter," and so the call to
Scanner.nextLine returns after reading that newline.

You will encounter the similar behaviour when you use Scanner.nextLine
after Scanner.next() or any Scanner.nextFoo method (except nextLine
itself).

The answer and the workaround are here.

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