我试图在Java的上下文中学习面向对象的编程.我正在编写一个相当简单的代码,但是我收到了这个错误:
Exception in thread "main" java.lang.NullPointerException
at Advisor_score.Rating.Score(Rating.java:12)
at Advisor_score.Rating.main(Rating.java:25)
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
package Advisor_score;
public class Rating {
double [] Ratings;
double sum;
double raw_advisor;
double advisor_score;
public Rating (double [] x){
double [] Ratings = x;
}
public double Score(){
for(int i=2;i<Ratings.length;i++){
sum+=Ratings[i];
}
raw_advisor=((sum-(3*(Ratings.length-2)))/4);
advisor_score= 2.5+(2.5*(1-Math.pow(Math.E, -.5*raw_advisor)));
return advisor_score;
}
public void print(){
System.out.println(advisor_score);
}
public static void main(String[] args){
double p1_1[] = {101,1,1,1.5,.5};
Rating d = new Rating(p1_1);
d.Score();
d.print();
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在看这几个小时,无法弄清楚代码的问题.我是编程新手可以有人帮助我吗?提前致谢!
sep*_*p2k 11
public Rating (double [] x){
double [] Ratings = x;
}
Run Code Online (Sandbox Code Playgroud)
在这里,您将声明一个局部变量Ratings并分配x给它.之后,变量超出了范围.
你想要做的是Ratings = x;,它将实例变量设置Ratings为x而不是创建一个新的和未使用的局部变量.
这是你的代码,格式很好,修复了错误:
package com.yourdomain.advisor.score;
public class Rating{
double[] ratings;
double sum;
double rawAdvisor;
double advisorScore;
public Rating(final double[] x){
this.ratings = x;
}
public double score(){
for(int i = 2; i < this.ratings.length; i++){
this.sum += this.ratings[i];
}
this.rawAdvisor = (this.sum - 3 * (this.ratings.length - 2)) / 4;
this.advisorScore =
2.5 + 2.5 * (1 - Math.pow(Math.E, -.5 * this.rawAdvisor));
return this.advisorScore;
}
public void print(){
System.out.println(this.advisorScore);
}
public static void main(final String[] args){
final double p1_1[] = { 101, 1, 1, 1.5, .5 };
final Rating d = new Rating(p1_1);
d.score();
d.print();
}
}
Run Code Online (Sandbox Code Playgroud)
您正在为未使用的局部变量而不是字段分配值.
我根据java约定添加了一些更改:
请参阅Sun Java命名约定
另外,帮自己一个忙:使用像Eclipse这样的IDE 并打开代码格式
| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |