显示java.lang.NullPointerException?

时间:2012-12-04 00:58:32

标签: java arrays

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadCellPhones {
    public static void main(String Args[]) throws IOException {
        Scanner s = new Scanner(System.in);
        File Input = new File("Cellphone.txt");
        Scanner f = new Scanner(Input);

        String[] Cells = new String[20];
        Double[] Amounts = new Double[20];

        Double threshold = printmenu();
        int number = 0;

        while (f.hasNext()) {
            Cells[number] = f.next();
            Amounts[number] = f.nextDouble();
            number++;
        }

        System.out.println("NUMBER\tArmount");

        for (int i = 0; i < Amounts.length; i++) {
            if (Amounts[i] > threshold)// THIS IS WHERE THE NULLPOINTER
            // EXCEPTION OCCURS
            {
                System.out.print(Cells[i] + "\t" + Amounts[i]);
            }
        }
    }

    static Double printmenu() {
        Scanner s = new Scanner(System.in);

        System.out.print("Enter the filename: ");
        String Filename = s.nextLine();

        System.out.print("Cell Bill Threshold: ");
        Double threshold = s.nextDouble();

        return threshold;
    }
}

因此,我尝试做的是从文件中读取数据,将数据存储在2个数组中,如果Amounts数组值大于为阈值变量输入的值,则打印出数组。但是当我尝试运行该程序时,弹出nullpointer错误,任何想法为什么?

3 个答案:

答案 0 :(得分:2)

问题是你读的记录少于20个。

Amounts数组中的每个Double都默认值为null。当java进行拆箱以便将Amounts[i]threshold进行比较时,它会尝试取消引用此空值,从而创建异常。

解决方案是标记成功读入的值的数量,并仅将这么多值与阈值进行比较。

答案 1 :(得分:0)

如果阈值小于20,则for循环将继续到Amounts数组的末尾,其中包括未初始化的双精度数。根据你想要的功能,我建议循环直到我

答案 2 :(得分:0)

无法保证文件数据的数量为20。

所以改变你的循环限制计数器

//for(int i=0;i<Amounts.length;i++)
for(int i=0;i<number;i++)  //variable number has a count of file's data
祝你好运