英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论