[英]'in cannot be resolved' Java Scanner
我最近一直在学习Java,并决定要了解用户输入是一项小任务,因此我将为用户输入的数字创建一个时间表生成器。 这是代码:
import java.util.Scanner;
public class Tables {
public static void main( String[] args) {
int IFactor, num, ans;
Scanner Input = new Scanner(System.in);
try {
System.out.println("Please enter a number to be the factor: ");
String SFactor = Input.next();
IFactor = Integer.parseInt(SFactor);
num = 1;
while (num < 11) {
ans = num * IFactor;
System.out.println(num + " * " + IFactor + " = " + ans);
num++;
}
}
finally {
in.close();
}
}
}
当我使用Eclipse声明扫描仪“输入”时,最初是有一个错误,指出存在资源泄漏并且没有关闭。 我做了一些研究,发现插入了一个try {}和一个finally {}和“ in.close();”。 会解决问题。 但是,情况并非如此,因为我现在遇到错误:“无法解决”。
任何帮助将非常感激! 谢谢!
中未分配任何内容。 您将不得不关闭名为Input的扫描仪。
try{
// code
}
catch(Exception ex)
{
// Exception handling
}
finally{
if(Input!=null){
Input.close();
}
}
您的变量名称是Input
并且您正在尝试in.close()。 它应该是:
finally {
Input.close();
}
尝试使用资源是关闭AutoCloseable
资源(如Scanner
)的现代/推荐方法。 例如
try (Scanner Input = new Scanner(System.in)) {
// do stuff with Input
}
并跳过finally
块。 在try
块结束时或更早(如果引发异常),将关闭Input
。 而且您不必担心。
检查有效Java中的第7项,以避免finally
阻塞的原因
尝试
finally {
Input.close();
}
代替。 请注意,在Java中,变量名通常以小写字母开头(类以大写字母开头)-因此最好将该变量重命名为`input?。 也一样
问题是
finally {
in.close();
}
您可以尝试使用try-with-resources的代码。 它是更多的java8,并且您不需要finally子句:
try(Scanner Input = new Scanner(System.in);)
{
System.out.println("Please enter a number to be the factor: ");
String SFactor = Input.next();
IFactor = Integer.parseInt(SFactor);
num = 1;
while (num < 11) {
ans = num * IFactor;
System.out.println(num + " * " + IFactor + " = " + ans);
num++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.