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");
}
}
}