The end goal is to create a program that reads a text file and then determines the lowest, highest, and average of all the numbers in the text file. My program has no errors, but upon running it throws this error:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:417)
at java.lang.Integer.parseInt(Integer.java:499)
at PrintWriter.main(PrintWriter.java:40)
My code is below. If anyone could help me figure this out it would be much appreciated!
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PrintWriter
{
public static void main(String[] args)
{
System.out.println("Enter the name of the file you wish to open");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.nextLine();
Scanner inputStream = null;
String[] numbers = new String[100];
int index = 0, count = 0, average = 0, total = 0;
String regex = "[0-9]+";
//Open and read text file
try
{
inputStream = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
numbers[index] = line;
index++;
count++;
}
int lowest = Integer.parseInt(numbers[0]);
int highest = Integer.parseInt(numbers[0]);
for (index = 0; index < numbers.length; index++)
{
if (Integer.parseInt(numbers[index]) <= lowest)
{
lowest = Integer.parseInt(numbers[index]);
}
else if (Integer.parseInt(numbers[index]) >= highest)
{
highest = Integer.parseInt(numbers[index]);
}
total = total + Integer.parseInt(numbers[index]);
count++;
}
average = Math.round(total / count);
System.out.println("\nThe average of all the numbers is " + average + ". The lowest number was " + lowest + ". The highest number was " + highest);
System.out.println("\nThe numbers are listed below");
for (index = 0; index < numbers.length; index ++)
{
if (numbers[index].matches(regex));
{
System.out.println(numbers[index]);
}
}
}
}
As you initialized your array to 100 elements and your loop iterates through all the array values (for (index = 0; index < numbers.length; index++)), at some point, you will be trying to parse null values which causes the exception. So the loop should iterate until count and not array length. You don't have to increment count inside the for loop as you already have counted all the elements in the previous while loop. Also, you don't have to call Integer.parseInt 5 times in the loop, just get that integer once and store it in an int variable, then reuse the variable:
for (index = 0; index < count; index++) {
int value = Integer.parseInt(numbers[index]);
if (value < lowest) {
lowest = value;
} else if (value > highest) {
highest = value;
}
total = total + value;
}