我在第23行和第78行Main和getRank()分別得到一個空指針異常錯誤。這發生在我重組代碼並使方法getRank()時發生。此代碼編譯並運行之前我將代碼移動到getRank()方法,我相信這個錯誤是由於變量未正確初始化。Java語言空指針異常錯誤
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;
}
}
這就是問題所在,一旦我從該行代碼中刪除字符串,代碼就可以正常工作。謝謝。 – 2012-04-15 14:05:40