老师,你好!麻烦帮忙看下这个代码有什么问题?谢谢!
import java.util.Scanner;
public class HomeWorkTest3 {
/**
* 修改指定位置的数据
* @param f
* @param index
* @param newScore
*/
public void update(float[] f,int index,float newScore) {
Scanner sc=new Scanner(System.in);
f[index]=newScore;
System.out.println("修改后:");
System.out.println("成绩为:");
for(float n:f) {
System.out.print(n+" ");
}
}
public static void main(String[] args) {
HomeWorkTest3 hwt3=new HomeWorkTest3();
Scanner sc=new Scanner(System.in);
float[] f= {98,65,75,83,87};
int index=0;
float newScore=0;
System.out.println("修改前:");
System.out.println("成绩为:");
for(float n:f) {
System.out.print(n+" ");
}
System.out.println();
do {
System.out.println("请输入要修改数据的位置(从0开始):");
try{
index=sc.nextInt();
}catch(java.util.InputMismatchException e) {
System.out.println("输入的数据类型有误,请重新输入!");
sc.next();
}
}while(index<0 | index>f.length-1);
System.out.println("请输入新数据:");
try {
newScore = sc.nextInt();
}catch(java.util.InputMismatchException e) {
System.out.println("输入的数据类型有误,请重新输入!");
sc.next();
}
hwt3.update(f,index,newScore);
}
}
正在回答 回答被采纳积分+1
同学你好,对于同学的两个问题,可以采用如下思路,这里可以编写一个方法来判断输入的是否是数字,如果不是数字,可以进行给出提示信息,返回false,如果是数字,返回true,具体如下:

然后在主方法中调用该方法,进行循环判断。
修改后的代码如下:
import java.util.Scanner;
public class HomeWorkTest3 {
/**
* 修改指定位置的数据
*
* @param f
* @param index
* @param newScore
*/
public void update(float[] f, int index, float newScore) {
Scanner sc = new Scanner(System.in);
f[index] = newScore;
System.out.println("修改后:");
System.out.println("成绩为:");
for (float n : f) {
System.out.print(n + " ");
}
}
public static void main(String[] args) {
HomeWorkTest3 hwt3 = new HomeWorkTest3();
Scanner sc = new Scanner(System.in);
float[] f = { 98, 65, 75, 83, 87 };
int index = 0;
float newScore = 0;
System.out.println("修改前:");
System.out.println("成绩为:");
for (float n : f) {
System.out.print(n + " ");
}
System.out.println();
do {
System.out.println("请输入要修改数据的位置(从0开始):");
while (!hwt3.isNum(sc)) {
sc = new Scanner(System.in);
}
index = sc.nextInt();
} while (index < 0 || index > f.length - 1);
System.out.println("请输入新数据:");
while (true) {
if (hwt3.isNum(sc)) {
newScore = sc.nextInt();
hwt3.update(f, index, newScore);
break;
}
sc = new Scanner(System.in);
System.out.println("输入的数据类型有误,请重新输入");
}
}
private boolean isNum(Scanner scanner) {
if (scanner.hasNextInt()) {
System.out.println("输入的是数字");
return true;
} else {
System.out.println("输入的不是数字,请重新输入");
return false;
}
}
}如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星