try-catch把数组包围起来了,导致作用不到return,return语句应写在哪里,该怎么写
来源:3-4 项目作业
慕村8299611
2022-12-16 11:57:07
package com.imooc.datamanage;
import java.util.Scanner;
public class AchieveManage {
public float[] intiScore() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要存储的数学成绩数量:");
try {
int n = sc.nextInt();
float[] f = new float[n];
for (int i = 0; i < f.length; i++) {
System.out.println("请输入第" + (i + 1) + "个数据");
f[i] = sc.nextFloat();
}
} catch (java.util.InputMismatchException e) {
System.out.println("你输入的数据有误!请重新输入");
sc.next();
}
return f;
}
public static void main(String[] args) {
AchieveManage stu = new AchieveManage();
float[] a = stu.intiScore();
for (float n : a) {
System.out.print(n + " ");
}
}
}
1回答
好帮手慕小蓝
2022-12-16
同学你好,只需要将数组的声明放在try代码块的外面即可。处理之后的代码如下:
public class AchieveManage {
public float[] intiScore() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要存储的数学成绩数量:");
float[] f = null;
try {
int n = sc.nextInt();
f = new float[n];
for (int i = 0; i < f.length; i++) {
System.out.println("请输入第" + (i + 1) + "个数据");
f[i] = sc.nextFloat();
}
} catch (java.util.InputMismatchException e) {
System.out.println("你输入的数据有误!请重新输入");
sc.next();
}
return f;
}
}祝学习愉快~
相似问题