在关闭Scanner类时出现错误。

huangapple go评论65阅读模式
英文:

Getting error while closing scanner class

问题

我在Java中关闭扫描器时遇到了一个错误:
错误是:无法解析in

以下是代码行:

System.out.println("请输入您的数字:");
number = scan.nextInt();
in.close();
英文:

I am getting an error while close scanner in java:
the error is: in cannot be resolved

here is the lines of code:

System.out.println("Enter your number: ");
number = scan.nextInt();
in.close();

答案1

得分: 2

你忘记添加这行代码:

Scanner in = new Scanner(System.in);

更新后的代码:

 Scanner in = new Scanner(System.in);
 System.out.println("请输入你的数字:");
 int number = in.nextInt();
 in.close();

就是这样。

英文:

You forgot to add this line :

Scanner in = new Scanner(System.in);

Updated code :

 Scanner in = new Scanner(System.in);
 System.out.println("Enter your number: ");
 int number = in.nextInt();
 in.close();

That's all.

答案2

得分: 1

请更新您的代码,使用以下内容初始化Scanner类 -

try (Scanner in = new Scanner(System.in)) {
     System.out.println("Enter your number: ");
     int number = in.nextInt(); 
}

就是这样!!上述代码仅适用于Java8,因为我们使用了Java8的资源管理(try-with-resources)概念。这将在try块结束时自动关闭资源,无需手动调用close方法。

英文:

Please update your code to initialize the Scanner class using below -

try(Scanner in = new Scanner(System.in)) {
     System.out.println("Enter your number: ");
     int number = in.nextInt(); 
}

Thats it !! The above code will work on Java8 only as we are using Java8 try with resource concepts. This will automatically takes care of closing the resource after the try block end is reached. No need to manually call the close method.

huangapple
  • 本文由 发表于 2020年10月3日 13:34:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64181072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定