这个我看不出来,麻烦老师了
来源:8-2 项目作业
慕楠枫桥
2021-03-28 17:15:26
package Project.operation;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* 谭昌
* 2021/3/28
*/
public class Score {
public void displayMenu() {
System.out.println("***********************************");
System.out.println(" 1--初始化数学成绩");
System.out.println(" 2--求成绩的平均数");
System.out.println(" 3--统计成绩大于85分的人数");
System.out.println(" 4--修改指定位置处的成绩");
System.out.println(" 5--打印输出所有的成绩");
System.out.println(" 0--退出");
System.out.println("************************************");
}
public double[] initScore() {
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("请输入要存储的数学成绩的数量:");
try {
input = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("输入有误,不能有非数字!");
sc.next();
}
double a[] = new double[input];
for (int i = 0; i < input; i++) {
System.out.println("请输入第" + (i + 1) + "个数据");
a[i] = sc.nextInt();
}
return a;
}
public void excellent(double[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (i > 85) {
count++;
}
}
System.out.print("成绩大于85分的人数为:" + count);
}
public void modify(double[] a, double n, int k) {
for (int i = 0; i < a.length; i++) {
if (i == k) {
a[i] = n;
}
break;
}
}
public static void main(String[] args) {
Score score = new Score();
Scanner sc = new Scanner(System.in);
double[] a = null;
int k = 0;
double n = 0;
int temp;
while (true) {
score.displayMenu();
System.out.println("请输入对应的数字进行操作:");
try {
temp = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("输入错误,请重新输入!");
sc.next();
continue;
}
switch (temp) {
case 0:
System.out.println("退出程序!");
break;
case 1:
score.initScore();
break;
case 2:
System.out.println("数学平均成绩为:" + score.averageScore(a));
break;
case 3:
score.excellent(a);
break;
case 4:
System.out.println("修改前成绩为:");
print(a);
System.out.println();
System.out.println("请输入要修改数据的位置(从零开始):");
try {
n = sc.nextDouble();
System.out.println("请输入新数据:");
k = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("输入有误!");
sc.next();
break;
}
System.out.println("修改后的成绩为:");
score.modify(a, n, k);
break;
case 5:
score.print(a);
break;
default:
System.out.println("输入有误!!");
}
}
}
public static void print(double[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
private double averageScore(double[] a) {
double average = 0;
double sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
average = sum / a.length;
return average;
}
}
1回答
好帮手慕阿园
2021-03-28
同学你好,同学指的是初始化数组后进行其他操作报空指针异常吗,如果是,当在初始化方法中返回了数组a
而同学在调用该方法时没有使用数组接收,导致在接下来的操作中a为null
所以这里需要用数组去接收,如下
如果同学指的不是该问题,还建议同学具体描述下是哪里看不出来呢
祝学习愉快~
相似问题
回答 1
回答 1