首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java多次使用Scanner

Java多次使用Scanner
EN

Stack Overflow用户
提问于 2014-11-06 20:22:33
回答 2查看 18.9K关注 0票数 4

我经常遇到这个问题。当我多次使用一个扫描器时,它没有从用户那里得到输入。

代码语言:javascript
复制
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();

当我运行这段代码时,结果如下:

1

12

2

321

3

4

aa

如你所见,它在第三次输入时跳过。为什么会发生这种情况?我通过使用新的扫描仪来解决这个问题,有时我有5-6个不同的扫描仪,它看起来非常复杂。另一个问题是:有一个错误“资源泄漏:扫描永远不会关闭”。我真的很困惑。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-06 20:28:10

使用next API而不是nextLine,因为当您执行nextInt时,按enter键,它会生成数字+ \n,而nextInt只会接受一个整数,而不会接受\n,这反过来会传递给下一个输入,即try3,这就是为什么它会被跳过。

代码语言:javascript
复制
        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();
票数 3
EN

Stack Overflow用户

发布于 2014-11-06 20:35:13

那么,对于第一个问题,请使用

scan.next()

实例化使用

scan.nextLine();

对于第二个问题,我建议使用try,假设您需要关闭扫描,因为您的编译器正在警告:“资源泄漏:扫描从未关闭”

代码语言:javascript
复制
Scanner scanner= null;
  try {
    scanner= new Scanner(System.in);

  }
  finally {
    if(scanner!=null)
    scanner.close();
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26779393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档