The*_*ess 1 java arrays filereader
我有一段时间没有碰过Java,所以我对一些细节有点生疏.
我试图从一个充满数字的文件中读取所有自己的行.文件中的第一个数字告诉我文件中有多少其他数字,所以我可以适当调整我的数组大小.我试图获取这些数字,并将它们放在一个int数组中,但我在return语句中不断收到"错误:可变数据可能尚未初始化".我知道这必须是简单的事情,但我不能为我的生活找出我做错的简单事情.
public static int[] numbers(String filename)
{
int[] data;
try
{
FileReader input = new FileReader(filename);
BufferedReader buffer = new BufferedReader(input);
int arraySize = Integer.parseInt(buffer.readLine());
data = new int[arraySize];
for (int x = 0; x < arraySize; x++)
{
data[x] = Integer.parseInt(buffer.readLine());
}
buffer.close();
}
catch(Exception e)
{
System.out.println("Error reading: "+e.getMessage());
}
return data;
}
Run Code Online (Sandbox Code Playgroud)
如果try块中抛出异常,则data可能在返回时未初始化.
当你声明它时,将它初始化为某个东西,即使值是null,也要满足编译器.
另一方面,看起来这IOException是唯一被抛出的例外.或者,您可以将您的方法声明为throw IOException,并删除try- catchblock,以便data在return执行语句时始终初始化.您当然需要在调用numbers方法的方法中捕获异常.
| 归档时间: |
|
| 查看次数: |
382 次 |
| 最近记录: |