java.lang.nullpointerException?

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

所以我想做的是从文件中读取数据,将数据存储在两个数组中,如果 Amounts 数组值大于为阈值变量输入的值,则打印出数组。但是当我尝试运行该程序时,会弹出空指针错误,知道为什么吗?

最佳答案

问题是您读入的记录少于 20 条。

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

解决方案是标记有多少个值被成功读入,并且只将这些值与阈值进行比较。

关于java.lang.nullpointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694472/

相关文章:

java - 如何在android studio中恢复到旧的包样式?

java - Spring Flux(或 Java Stream)作为左连接合并

python - Python 的 List 是如何实现的?

arrays - 在Perl 6中,我可以使用数组作为哈希键吗?

java - 整型和浮点型字面量指向和使用?

Java = Getter/Setter = 这是否会在运行时和访问时增加 "object size"(CPU 周期?)

python - pretty-print (2D 阵列、盒子)

c++ - 如何将值列表传递给需要数组的函数?

c - 将数组传递给c中的函数

java - 在 android AsyncTask 中获取数据并更新 UI View