[英]Getting “Variable data not initialized” error even though it's initialized
我已经有一段时间没有接触Java了,所以在某些细节上我有些生疏。
我试图从一个充满数字的文件中读取所有数据。 文件中的第一个数字告诉我文件中还有多少个其他数字,因此我可以适当地调整数组大小。 我试图将这些数字放入一个整数数组中,但是我在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;
}
如果try
块中引发了异常,则data
可能在返回时尚未初始化。
声明它时将其初始化为某种值,即使该值为null
,也可以满足编译器的要求。
另一方面, IOException
是唯一要抛出的异常。 或者,您可以声明您的方法引发IOException
,并删除try
- catch
块,以便在执行return
语句时始终初始化data
。 您当然需要在调用您的numbers
方法的方法中捕获异常。
之所以会出现此错误,是因为您正在try块中初始化数据数组,但是如果try块捕获到异常,则该数据数组可能不会初始化,但无论如何都会返回。
在try-catch之外初始化数组:
例如:
int[] data = new int[1]; //default initialization
这是由于在try / catch块中进行了初始化,如果在try / catch块中进行初始化之前引发了异常,则可能永远无法实例化该数组。
我认为只需在声明中将数组长度设置为1或null即可解决您的问题
int[] data = new int[1];
try
// the rest
要么
int[] data = null;
我有两个与其他答案稍有不同的建议(仅略有不同)。 如果存在异常,那么您应该1)抛出一个异常(例如RuntimeException
),或者2)仅返回null
(我猜您不希望实际抛出异常)。
public static int[] numbers(String filename)
{
BufferedReader buffer = null;
try
{
final FileReader input = new FileReader(filename);
BufferedReader buffer = new BufferedReader(input);
final int arraySize = Integer.parseInt(buffer.readLine());
final int[] data = new int[arraySize];
for (int x = 0; x < arraySize; x++)
{
data[x] = Integer.parseInt(buffer.readLine());
}
buffer.close();
return data;
}
catch(Exception e)
{
System.out.println("Error reading: "+e.getMessage());
}
finally{
// a NumberFormatException may be thrown which will leave
// the buffer open, so close it just in case
if(buffer != null)
buffer.close();
}
// else there was an exception, return null
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.