简体   繁体   中英

Cant figure out how to solve exception in java program

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

Some of your Strings MAY not contain a parsable integer. Probably, they may contain whitespaces. So use trim method to get rid of that.

From javadoc :

public String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

Change this part of code

     int lowest = Integer.parseInt(numbers[0].trim());
     int highest = Integer.parseInt(numbers[0].trim());
     for (index = 0; index < numbers.length; index++)
     {

         if (Integer.parseInt(numbers[index].trim()) <= lowest)
         {
             lowest = Integer.parseInt(numbers[index].trim());
         }
         else if (Integer.parseInt(numbers[index].trim()) >= highest)
         {
             highest = Integer.parseInt(numbers[index].trim());
         }

         total = total + Integer.parseInt(numbers[index].trim());
         count++;
     }

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

您的文本文件包含的行不是数字(带有空格或字母),或者文件中没有100个数字。

The file doesn't specify, how many numbers it holds. Due to this, only a part of the array is filled with strings from the file. These are parsed correctly. But at some point the code reaches the part of the array that isn't filled with lines. And then this call happens: Integer.parseInt(someString) , where someString is null , causing the NullPointerException . To fix this you could either add a counter for read lines and use this counter instead of numbers.length , or check if the String is null before parsing an Integer from it.

Java Code

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestProgram {

    public static void main(String[] args) throws FileNotFoundException {

        String line="";
        ArrayList<Integer> arl = new ArrayList<Integer>();
        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()) {
            line = inputStream.nextLine();
            numbers[index] = line;
            index++;
            count++;
            Pattern pattern = Pattern.compile("[0-9]+");
            Matcher m = pattern.matcher(line);

            while (m.find()) { 
                int n =Integer.parseInt(m.group()); 
                System.out.println(n);
                arl.add(n);

            }
        }

        Collections.sort(arl);
        System.out.println(arl);
        int lowest = arl.get(0);
        int highest = arl.get(arl.size()-1);
        System.out.println("Lowest is: " + lowest );
        System.out.println("highest is: " + highest );
        total =  arl.size();

        Integer sum = 0;
        for (Integer mark : arl) {
            sum += mark;
        }
        int avg = sum /arl.size();
        average = Math.round(total / count);

        System.out.println("\nThe average of all the numbers is " + avg
                + ". The lowest number was " + lowest
                + ". The highest number was " + highest);
        System.out.println("\nThe numbers are listed below");

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM