gpt4 book ai didi

java - 编译错误: variable might not have been initialized

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:39 25 4
gpt4 key购买 nike

我正在尝试创建一种方法,为文件内的每个字符添加一个变量。如果文件是:

abcd
abc
ab

然后在函数运行该变量后,它将返回等于 9。

这是我到目前为止的代码:

public static double getRow(String filename) {
double size = 0;
File f;
Scanner infile;
try{
f = new File(filename);
infile = new Scanner(f);
}
catch (IOException e){
System.out.println("Error opening the file");
//System.exit(0); not good
}
while(infile.hasNext()) {
size++;
}
infile.close();
return size;

}

但我一直收到infile尚未初始化。我不确定如何获得我想要的解决方案。

最佳答案

因为您是在 try block 中初始化 infile,所以如果 try 中出现任何问题,当您尝试在 catch block 之后使用 infile 时,它永远不会被初始化。

您想要做的是让所有处理都在 try block 中进行,包括循环和关闭 infile:

public static double getRow(String filename) {
double size = 0;
File f;
Scanner infile;
try {
f = new File(filename);
infile = new Scanner(f);
while(infile.hasNext()) {
size++;
}
infile.close();
}
catch (IOException e) {
System.out.println("Error opening the file");
//System.exit(0); not good
}
return size;
}

关于java - 编译错误: variable might not have been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com