我分别在 Main 和 getRank() 的第 23 行和第 78 行收到空指针异常错误。当我重新组织代码并创建方法 getRank() 时,发生了这种情况。该代码在我将代码移至 getRank() 方法之前编译并运行,我相信此错误是由于变量未正确初始化所致。
import java.io.*;
import java.util.*;
public class NameRecord
{
private static String num, name = "dav";
private static String [] fields;
private static int [] yearRank;
private static boolean match;
private static int getInts, marker, year, max;
public static void main( String[] args)
{
java.io.File file = new java.io.File("namesdata.txt");
try
{
Scanner input = new Scanner(file);
while (input.hasNext())
{
String num = input.nextLine();
if(match = num.toLowerCase().contains(name.toLowerCase()))
{
getRank();//My Problem I believe
getBestYear(marker);
System.out.printf("%s %d %d\n",fields[0],year,max);
}
}
}
catch(FileNotFoundException e)
{
System.err.format("File does not exist\n");
}
}
public static int getRank()
{
fields = num.split(" ");
max = 0;
for (int i = 1; i<12; i++)
{
getInts = Integer.parseInt(fields[i]);
if(getInts>max)
{
max = getInts;
marker = i;
}
}
return max;
}
}
最佳答案
全局 num 未初始化,因此等于 null。在 mailn() 中,您创建一个新的局部变量,该变量不会暴露给 getRank()。如果您想使用它,请将其作为参数传递 getRank(num)
关于Java语言空指针异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10162589/