-2

I am pretty new to Java and I cannot seem to figure out why I am getting this error message relating to this error message: File not found. Exception in thread "main" java.lang.NullPointerException at Project1.main(Project1.java:24). Any help would be appreciated. I have tried running through command prompt as well as an online java compiler and both tell me that there is not a file to be found.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Project1 {

   public static void main(String[] args) 
   {
       // create file object
       File file = new File("input.txt");

       // create a scanner object
       Scanner scan = null;
        try 
        {
           scan = new Scanner(file);
        } 
       catch (FileNotFoundException e) 
       {
           System.out.println("File not found.");
       }

       // take number of men or women from file - first line
       int num = scan.nextInt();
       
       // create string array of size number of men to save men preference
       String[] menPreferenceArray = new String[num];
      
      // create string array of size number of women to save women preference
       String[] womenPreferenceArray = new String[num];

       // point to next line
       
       scan.nextLine();
       // loop till 2*num lines
       for (int i = 0; i < 2 * num; i++) 
       {
           // take first 3 preference and save to men preference array
           if (i < num)
               menPreferenceArray[i] = scan.nextLine();
           else
               // take next 3 preference and save to women preference array
               womenPreferenceArray[i - num] = scan.nextLine();
       }

       // variable to count prefectMatch
       int perfectPairNum = 0;

       // read till file has next line
       while (scan.hasNext()) 
       {
           // take a marriage pair as string
           String marriage = scan.nextLine();
           // split by space
           String[] pair = marriage.split(" ");
           // reverse the pair
           String marriageReverse = pair[1] + " " + pair[0];

           // count variable to check if men and women has same preference
           int count = 0;
           // loop through the men and women preference array
           for (int j = 0; j < 2 * num; j++) 
           {
               if (j < num) 
               {
                   // take first preference string using substring and check if the marriage pair
                   // is equal to preference string
                   if (menPreferenceArray[j].substring(0, 3).equals(marriage))
                       // increment count by 1
                       count++;
               } else 
               {
                   // take first preference string using substring
                   if (womenPreferenceArray[j - num].substring(0, 3).equals(marriageReverse)) {
                       // increment count by 1
                       count++;
                   }
               }
           }
           // if count equal to 2 means, both men and women have same preference, so
           // marriage is stable
           if (count == 2) 
           {
               // increment variable to check all marriages are stable
               perfectPairNum++;
           } 
           else 
           {
               // if count not equal to 2 means, both men or women do not have same preference
               // . so marriage is unstable
               System.out.println("Unstable " + marriage);
           }
       }
       // close scanner object
       scan.close();

       // if all marriages are stable, then output stable
       if (perfectPairNum == num) 
       {
           System.out.println("Stable");
       }
   }

}
  • 1
    Robert’s answer is the right one. If the file cannot be found, why would you want the program to continue? What useful function can it possibly perform without a file to read? – VGR Feb 11 '21 at 22:48

2 Answers2

2

Don't just print a message when you catch an exception and continue on.

Here you catch the FileNotFoundException cause "input.txt" does not exist (at least not in the current directory). You print a message but still try to use scan, which never got initialized, as its constructor threw. So scan is null, and that's why you get the NullPointerException when you use scan.

To fix this, exit the program when you catch the exception. Since you need that input file, there's no way to continue without it.

Either change the catch block:

Scanner scan = null;
try 
{
    scan = new Scanner(file);
} 
catch (FileNotFoundException e) 
{
    System.out.println("File not found.");
    return;  // Exit the program
}

Or don't catch the exception at all and declare that main can throw FileNotFoundException. In this case the program will error out for you.

public static void main(String[] args) throws FileNotFoundException
{
    // ...
    scan = new Scanner(file);
    // ...

To avoid an error with files, specify the absolute path to the file, e.g, "/home/me/input.txt" or "C:\\Users\\me\\input.txt" instead of just "input.txt".

Robert
  • 7,394
  • 40
  • 45
  • 64
0

If input.txt doesn't already exist, you can create it like so:

File file = new File("input.txt");
file.createNewFile();

Here is a link to the docs: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()

katzenhut
  • 1,742
  • 18
  • 26
  • True, but what do you read from that file? Either you crash on reading data that's not there, or you process garbage. – Robert Feb 11 '21 at 22:49