Java多次使用扫描仪 [英] Java Using Scanner Multiple Times

查看:65
本文介绍了Java多次使用扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到这个问题.当我多次使用扫描仪时,它没有得到用户的输入.

I am having this problem a lot. When I use a Scanner a lot of times, it doesn't get input from user.

Scanner scan = new Scanner(System.in);

        System.out.println("1---");

        int try1 = scan.nextInt();

        System.out.println("2---");

        int try2 = scan.nextInt();

        System.out.println("3---");

        String try3 = scan.nextLine();

        System.out.println("4---");

        String try4 = scan.nextLine();

运行此代码时,结果如下:

When I run this code, result it :

1 ---

12

2 ---

321

3 ---

4 ---

aa

如您所见,它在第3个输入处跳过.为什么会这样呢?我使用新的扫描仪解决了这个问题,有时我有5-6台不同的扫描仪,而且看起来很复杂. 另一个问题是:出现错误资源泄漏:扫描从未关闭".我真的很困惑.

As you can see, it skipped at 3rd input. Why this is happening? I solve this problem by using new Scanners, sometimes I have 5-6 different Scanners and it looks so complicated. Another problem is : there is an error "Resource leak: scan is never closed". I am really confused.

推荐答案

使用next API而不是nextLine进行nextInt时,请按enter键,它会生成数字+ \ n,nextInt仅采用整数,不会取\ n,该字符又传递给下一个输入,即try3,这就是为什么它被跳过的原因.

Use next API rather than nextLine as when you do nextInt you press enter and it generates number + \n and nextInt is only going to take an integer and won't take \n which in turn gets passed to next input i.e. try3 which is why it gets skipped.

        Scanner scan = new Scanner(System.in);

    System.out.println("1---");

    int try1 = scan.nextInt();

    System.out.println("2---");

    int try2 = scan.nextInt();

    System.out.println("3---");

    String try3 = scan.next();

    System.out.println("4---");

    String try4 = scan.next();

这篇关于Java多次使用扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆