2012-04-15 96 views
0

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

回答

1

你的问题是与num,你在主声明一个局部变量,它隐藏了您的实例成员:

String num = input.nextLine(); 

你大概的意思是:

num = input.nextLine(); 
+0

这就是问题所在,一旦我从该行代码中删除字符串,代码就可以正常工作。谢谢。 – 2012-04-15 14:05:40

3

全局编号未初始化,因此等于空。在mailn()中,您创建了一个不暴露给getRank()的新局部变量。如果你想使用它,把它作为参数getRank(NUM)

+0

他只隐藏了类成员。它是没有初始化的类成员,但局部变量是。 – 2012-04-15 13:52:25

+0

这也工作。谢谢 – 2012-04-15 14:05:53

+0

您是第一个回答+1的人。 – Lion 2012-04-15 14:06:30