我在try-exception
之前声明了扫描仪填充
e,但由于某种原因它说变量可能未初始化?
Scanner infile;
try
{
infile = new Scanner(file);
}
catch(FileNotFoundException f)
{
System.out.println("Wrong File Path");
}
while (infile.hasNext())
{
System.out.print("Testing While loop");
最佳答案
考虑一下如果在 new Scanner
构造函数调用中抛出异常会发生什么。构造函数永远不会完成,因此 new Scanner(file) 不会产生值;那么infile
呢?
要纠正它,请将 while
循环移至 try
block 中:
Scanner infile;
try
{
infile = new Scanner(file);
while (infile.hasNext())
{
System.out.print("Testing While loop");
}
}
catch(FileNotFoundException f)
{
System.out.println("Wrong File Path");
}
毕竟,异常处理的目的是让它脱离主逻辑。
关于java - 变量可能未从扫描仪初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29983753/