无法弄清楚如何解决 java 程序中的异常
Cant figure out how to solve exception in java program
最终目标是创建一个读取文本文件的程序,然后确定文本文件中所有数字的最小值、最大值和平均值。我的程序没有错误,但在 运行 时抛出此错误:
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]);
}
}
}
}
您的某些字符串可能不包含可解析的整数。可能,它们可能包含空格。所以使用 trim
方法来摆脱它。
来自javadoc:
public String trim()
Returns a copy of the string, with leading and
trailing whitespace omitted.
更改这部分代码
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++;
}
您的文本文件包含一行不是数字(包含空格或字母),或者文件中没有 100 个数字。
该文件没有指定它包含多少个数字。因此,只有数组的一部分填充了文件中的字符串。这些被正确解析。但在某些时候,代码到达了数组中没有行的部分。然后发生此调用:Integer.parseInt(someString)
,其中 someString
是 null
,导致 NullPointerException
。要解决此问题,您可以为读取行添加一个计数器并使用此计数器代替 numbers.length
,或者在从中解析 Integer
之前检查 String
是否为 null
。
当您将数组初始化为 100 个元素并且循环遍历所有数组值时(for (index = 0; index < numbers.length; index++)),在某些时候,您将尝试解析导致异常的空值。所以循环应该迭代直到计数而不是数组长度。您不必在 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;
}
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");
}
}
最终目标是创建一个读取文本文件的程序,然后确定文本文件中所有数字的最小值、最大值和平均值。我的程序没有错误,但在 运行 时抛出此错误:
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]);
}
}
}
}
您的某些字符串可能不包含可解析的整数。可能,它们可能包含空格。所以使用 trim
方法来摆脱它。
来自javadoc:
public String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
更改这部分代码
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++;
}
您的文本文件包含一行不是数字(包含空格或字母),或者文件中没有 100 个数字。
该文件没有指定它包含多少个数字。因此,只有数组的一部分填充了文件中的字符串。这些被正确解析。但在某些时候,代码到达了数组中没有行的部分。然后发生此调用:Integer.parseInt(someString)
,其中 someString
是 null
,导致 NullPointerException
。要解决此问题,您可以为读取行添加一个计数器并使用此计数器代替 numbers.length
,或者在从中解析 Integer
之前检查 String
是否为 null
。
当您将数组初始化为 100 个元素并且循环遍历所有数组值时(for (index = 0; index < numbers.length; index++)),在某些时候,您将尝试解析导致异常的空值。所以循环应该迭代直到计数而不是数组长度。您不必在 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;
}
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");
}
}