我的代码中出现了java.lang.nullpointerexception错误。虽然我不确定为什么它不正确。我应该快速解决,但我似乎无法弄明白。似乎第45行中的数组给出了错误。任何帮助将不胜感激。提前谢谢。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class readFile
{
private String fileName;
private double lowestNum;
private double highestNum;
private double totalNum;
private double averageNum;
private int[] array;
public readFile(String input)
{
fileName = input;
lowestNum = 0;
highestNum = 0;
totalNum = 0;
averageNum = 0;
}
public void readArray() throws FileNotFoundException
{
Scanner s = new Scanner(new File(fileName));
array = new int[s.nextInt()];
for(int i = 0; i < array.length; i++)
{
array[i] = s.nextInt();
}
s.close();
}
\\ERROR IS HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public void findLowest()
{
lowestNum = array[0];
for(int i = 1; i < array.length; i++)
{
if(array[i] < lowestNum);
lowestNum = array[i];
}
System.out.println("Lowest number: " + lowestNum);
}
public void findHighest()
{
highestNum = array[0];
for(int i = 1; i < array.length; i++)
{
if(array[i] > highestNum);
highestNum = array[i];
}
System.out.println("Highest number: " + highestNum);
}
public void findTotalNum()
{
for(int i = 0; i < array.length; i++)
{
totalNum = totalNum + array[i];
}
System.out.println("Total of all numbers: " + totalNum);
}
public void findAverage()
{
averageNum = (totalNum / array.length);
System.out.println("Average of all numbers: " + averageNum);
}
}
public class NumberAnalysis
{
public static void main(String[] args) throws FileNotFoundException
{
String fileName = "Numbers.txt";
readFile myClass = new readFile(fileName);
myClass.findLowest();
myClass.findHighest();
myClass.findTotalNum();
myClass.findAverage();
}
}
答案 0 :(得分:3)
如果readArray()
是设置数组的方法,则必须在尝试使用数组之前调用该方法。
答案 1 :(得分:1)
您永远不会致电readArray
,因此您的array
永远不会被初始化。
答案 2 :(得分:0)
问题是你实例化你的对象,但你忘记了实例化数组。你应该这样做:
public static void main(String[] args) throws FileNotFoundException
{
String fileName = "Numbers.txt";
readFile myClass = new readFile(fileName);
myClass.readArray();
myClass.findLowest();
myClass.findHighest();
myClass.findTotalNum();
myClass.findAverage();
}
顺便说一下,你应该总是有一个以大写字母开头的类,它会让你的代码更具可读性。
答案 3 :(得分:0)
您必须调用readArray
方法,并且还应该为其提供参数filename
,以便Scanner
可以获取参数filename
。否则,它将生成FileNotFoundException