我分别在 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;
}
}