java数组空指针一场_java中对象数组的应用,空指针异常,求教。

展开全部

// 定义数组

Student[] scores = new Student[5];

你定义了一个e68a843231313335323631343130323136353331333337616633对象的数组,没有初始化的话 默认都是 null 就是 每个student 都是 null

int[] a = new int[4]  4个a默认都是0

可以这样处理import java.util.Scanner;

// 学生类

class Student {

// 属性:姓名,性别,年龄,专业,爱好

public String name;

public char sex;

public int age;

public String professionals;

public String hobby;

public double score;

}

class ScoreAreCalculated {

// 定义数组

Student[] scores = null;

ScoreAreCalculated(int count){

scores = new Student[count];

for (int i = 0; i 

scores[i] = new Student();

}

}

// 方法:求平均分

public double avgScore() {

double sum = 0.0;

double avg = 0.0;

for (int i = 0; i 

sum += scores[i].score;

}

avg = sum / scores.length;

return avg;

}

// 方法:求最高分

public double maxScore() {

double max = scores[0].score;

for (int i = 0; i 

if (max 

max = scores[i].score;

}

}

return max;

}

}

public class ScoreAreCalculatedTest {

public static void main(String[] args) {

// 创建Scanner对象

Scanner input = new Scanner(System.in);

System.out.print("请输入共有几名学生成绩要输入:");

int count = input.nextInt();

// 创建ScoreAreCalculated对象

ScoreAreCalculated score = new ScoreAreCalculated(count);

// 创建Studnet对象

Student stu = new Student();

// 输入学生成绩

for (int i = 0; i 

System.out.print("请输入第" + (i+1) + "名学生成绩:");

stu.score = input.nextDouble();

score.scores[i].score = stu.score; // 报错位置

}

// 调用avgScore方法

double avg = score.avgScore();

System.out.println("五位同学的平均分为:" + avg);

// 调用maxScore方法

double max = score.maxScore();

System.out.println("五位同学中最高分为:" + max);

// 关闭输入资源

input.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值