Reputation: 47
I am getting a Null Pointer Exception Error at line 23 and line 78 in Main and getRank() respectively. This occurred when I reorganized the code and made the method getRank(). This code compiled and ran previous to my moving the code to the getRank() method, and I believe this error is due to a variable not being initialized properly.
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;
}
}
Upvotes: 0
Views: 941
Reputation: 328598
Your problem is with num
, you declare a local variable in main which hides your instance member:
String num = input.nextLine();
You probably meant:
num = input.nextLine();
Upvotes: 1
Reputation: 30448
The global num is not initialized, and hence equals null. In mailn() you create a new local variable which is not exposed to getRank(). If you want to use it, pass it as parameter getRank(num)
Upvotes: 3