0

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;
    }
}
0

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

He is only hiding the class member. And it is the class member which is not initialised, but the local variable is.
You were the first to answer +1.
1

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();

1 Comment

This was the problem, once I deleted String from that line of code, the code worked. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.