gpt4 book ai didi

java - 空指针异常 Jcreator,Java

转载 作者:行者123 更新时间:2023-12-02 06:19:39 24 4
gpt4 key购买 nike

我在试图找出为什么会出现此错误时遇到了非常困难的时间。当我使用驱动程序文件来测试程序时,它严重失败。

这是我的代码:

import java.util.Scanner;
import java.lang.Math.*;
public class Histogram
{
private int[] arrayData;
private int[] arrayRange;
private final int LOW = 1;
private final int HIGH = 100;

public Histogram()
{
int[] arrayData = new int[11];
}

public void getInput()
{
int[] arrayRange = new int[11];
for(int count = 1; count < arrayRange.length; count++)
{
arrayRange[count] = count * 10;
}
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers from 1 to 100, Type -999 to quit.");
int nextNumb = input.nextInt();
while(nextNumb != -999)
{
if(nextNumb >= LOW && nextNumb <= HIGH)
{
for(int i = 0; i <= arrayRange.length; i++)
{
if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;
}
nextNumb = input.nextInt();
}
else arrayData[10]++;
nextNumb = input.nextInt();
}
}

public String starPrint(double count)
{
String star = "";
count = (Math.round(count) / 5);
for(int i = 1; i <= count; i++)
{
star = star + "*";
}

return star;
}

public String toString()
{
String results = " Range | Histogram" + "\n";
results = results + "1 - 10 | " + starPrint(arrayData[0]) + "\n";
results = results + "11 - 20 | " + starPrint(arrayData[1]) + "\n";
results = results + "21 - 30 | " + starPrint(arrayData[2]) + "\n";
results = results + "31 - 40 | " + starPrint(arrayData[3]) + "\n";
results = results + "41 - 50 | " + starPrint(arrayData[4]) + "\n";
results = results + "51 - 60 | " + starPrint(arrayData[5]) + "\n";
results = results + "61 - 70 | " + starPrint(arrayData[6]) + "\n";
results = results + "71 - 80 | " + starPrint(arrayData[7]) + "\n";
results = results + "81 - 90 | " + starPrint(arrayData[8]) + "\n";
results = results + "91 - 100 | " + starPrint(arrayData[9]) + "\n";
results = results + "Outliers: " + starPrint(arrayData[10]) + "\n";
return results;
}
}

我相信问题出在我的 getInput 方法中准确地说,就是这里:

if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;

尽管我是一名初学者程序员并且无法找到这个特定问题的解决方案,但我不知道它出了什么问题。感谢您提供的任何帮助!

最佳答案

public Histogram()
{
int[] arrayData = new int[11];
}

您正在构造函数中隐藏您的arrayData字段。这是创建一个与类的 arrayData 字段同名的局部变量,初始化它,然后立即丢弃它。当您稍后尝试在代码中使用该字段时,它为 null。去掉 int[] 部分。

请注意,您的下一个异常将是 ArrayIndexOutOfBoundsException ...您应该查看您的循环;)

关于java - 空指针异常 Jcreator,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124315/

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