gpt4 book ai didi

java.lang.nullpointerException?

转载 作者:行者123 更新时间:2023-11-30 04:35:07 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com