3 Replies - 149 Views - Last Post: 11 November 2018 - 10:25 AM Rate Topic: -----

#1 jgssjs12   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 19-October 18

Program can't find file....

Posted 11 November 2018 - 07:55 AM

I have written the below code to locate and display the minimum and maximum numbers from a text file. I also created the numbers.txt file and when running the program I get the message:

File Not Found
Exception in thread "main" java.lang.NullPointerException
at SearchFile.main(SearchFile.java:23)

Here is the code and a screen shot of where my file is located. What am I doing wrong?

import java.util.Scanner;
import java.util.*;
import java.io.*;

public class SearchFile 
{
	public static void main(String args[])
	{
		int max;
		int min;
		int search;
		
		Scanner inputFile = null;
		
		try
		{
			inputFile = new Scanner(new FileInputStream("numbers.txt"));
		}
		catch(FileNotFoundException e)
		{
			System.out.println("File Not Found");
		}
		max = inputFile.nextInt();
		min = max;
		while(inputFile.hasNextInt())
		{
			search = inputFile.nextInt();
			
			if(min > search)
				min = search;
			if(max < search)
				max = search;
		}
		System.out.println(min + " is the smallest number.");
		System.out.println(max + " is the largest number");
	}
}

Attached image(s)

  • Attached Image


Is This A Good Question/Topic? 0
  • +

Replies To: Program can't find file....

#2 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3604
  • View blog
  • Posts: 16,498
  • Joined: 20-September 08

Re: Program can't find file....

Posted 11 November 2018 - 08:03 AM

You're reading the current directory there so you need to know what that is

http://technojeeves....rectory-in-java
Was This Post Helpful? 0
  • +
  • -

#3 jgssjs12   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 19-October 18

Re: Program can't find file....

Posted 11 November 2018 - 10:19 AM

what do you mean? I'm sorry. I don't understand.
Was This Post Helpful? 0
  • +
  • -

#4 NormR   User is offline

  • D.I.C Lover
  • member icon

Reputation: 726
  • View blog
  • Posts: 5,524
  • Joined: 25-December 13

Re: Program can't find file....

Posted 11 November 2018 - 10:25 AM

The program is trying to read a file from the current directory that is set when the java program's execution starts. The link in post#2 gives code to find where the current directory is located.

The file needs to be moved to the current directory
or the path to the file that the program uses needs to be changed to refer to the file's location.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1