无法弄清楚如何解决java程序中的异常

时间:2015-05-06 23:06:58

标签: java printwriter

最终目标是创建一个程序来读取文本文件,然后确定文本文件中所有数字的最低,最高和平均值。我的程序没有错误,但在运行时抛出此错误:

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)

我的代码如下。如果有人能帮我解决这个问题,我将不胜感激!

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

5 个答案:

答案 0 :(得分:2)

你的一些字符串 MAY 不包含可解析的整数。可能,它们可能包含空格。因此,使用 if (NSUserDefaults.standardUserDefaults().integerForKey("Code") != nil) { } else{ var code = Int(arc4random_uniform(1000000000)) NSUserDefaults.standardUserDefaults().setInteger(code, forKey: "Code") } return NSUserDefaults.standardUserDefaults().integerForKey("Code") } 方法来摆脱它。

来自javadoc

  

public String trim()

     

返回字符串的副本,带有前导和   尾部空白省略。

更改此部分代码

trim

答案 1 :(得分:2)

当您将数组初始化为100个元素并且循环遍历所有数组值时(对于(index = 0; index&lt; numbers.length; index ++)),在某些时候,您将尝试解析空值这导致异常。所以循环应该迭代直到count而不是数组长度。你不必在for循环内增加计数,因为你已经计算了前一个while循环中的所有元素。此外,您不必在循环中调用Integer.parseInt 5次,只需获取该整数一次并将其存储在int变量中,然后重用该变量:

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

文件没有指定它拥有多少个数字。因此,只有一部分数组填充了文件中的字符串。这些都是正确解析的。但在某些时候,代码到达了数组中没有用线条填充的部分。然后发生此调用:Integer.parseInt(someString),其中someStringnull,导致NullPointerException。要解决此问题,您可以为读取行添加计数器并使用此计数器而不是numbers.length,或者在解析String之前检查null是否为Integer

答案 4 :(得分:0)

Java代码

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

    }
}
相关问题