我在一个Java程序中遇到了一个问题。线程"main"中出现异常。
java.lang.NullPointerException
at twoten.TwoTenB.<init>(TwoTenB.java:29)
at javapractice.JavaPractice.main(JavaPractice.java:32)
Java Result: 1
是我得到的错误。我真的需要一些帮助,因为我在这个地方卡了几个小时......
package twoten;
import java.util.Scanner;
public class TwoTenB {
public TwoTenB() {
double percentage;
double a[] = null;
double total = 0;
double var;
System.out.print("\tRESULT\n\n");
Scanner scan = new Scanner(System.in);
//double[] mark = new double[7];
for (int i = 0; i < 7; i++) {
System.out.print("\nMarks in subject " + (i + 1) + "\t:\t");
var = scan.nextDouble();
a[i] = var;
total = total + a[i];
//percentage = first * second * third * fourth * fifth * sixth * seventh * 100 / 700;
}
percentage = total * 100 / 700;
if (a[0] > 35 && a[1] > 35 && a[2] > 35 && a[3] > 35 && a[4] > 35 && a[5] > 35 && a[6] > 35 && percentage > 35) {
if (percentage >= 60) {
System.out.print("\nCongratulation!!! you've got FIRST dividion\n");
} else if (percentage >= 45 && percentage < 60) {
System.out.print("\nCongratulation!!! you've got SECOND dividion\n");
} else if (percentage >= 35 && percentage < 45) {
System.out.print("\nCongratulation!!! you've got THIRD dividion\n");
}
} else {
System.out.print("\nSORRY!!! you've FAILED\n");
}
}
}
这就是问题所在
double a[] = null;
因为a
是空',所以每次使用它时都会出现
空指针异常',直到你初始化它。所以这样。
a[i] = var;
将会失败。
一个可能的解决方案是在声明时将其初始化。
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO比解决这个异常更重要的是,你应该学会阅读堆栈跟踪,**理解它所说的内容,这样你就能发现问题并解决它。
java.lang.NullPointerException
这个异常意味着有一个值为 "空 "的变量被使用。如何解决?只要在使用前确保该变量不是 "空 "的。
at twoten.TwoTenB.
(TwoTenB.java:29)
这一行有两部分。
<init>
方法中,在包twoten
中声明的TwoTenB
类中。当你遇到SomeClassName.<init>
的错误信息时,意味着错误是在创建该类的新实例时抛出的,例如执行构造函数(在本例中这似乎是问题所在)。a[i] = var;
。从这一行开始,其他几行也会有类似的内容来告诉你错误产生的地方。所以当读到这里时。
at javapractice.JavaPractice.main(JavaPractice.java:32)
这意味着你试图在javapractice
包中声明的JavaPractice
类的main
方法中实例化一个TwoTenB
对象引用。