gpt4 book ai didi

java - 使用 nextFloat() 时线程 "main"java.util.InputMismatchException 中出现异常

转载 作者:行者123 更新时间:2023-12-02 11:45:22 27 4
gpt4 key购买 nike

所以我正在编写一个小程序来计算学生最好成绩的平均值,当我运行它时,我在线程“main”java.util.InputMismatchException中收到此错误异常。

我看到一篇文章说要使用 nextLine 然后使用 parseInt (在本例中为 parseFloat) ,但我不允许在这里使用它,所以我正在寻找关于我可以做什么的另一种意见.

代码:

导入java.util.Scanner;

公开课 G2a {

static float average(float[] vals) { //Returns the average of an array;
float avg = 0F;
for (int i = 0; i < vals.length; i++)
avg += vals[i];
return avg /= vals.length;
}

static int indexOfMin(float[] vals) { // Returns the index of the minimum;
int idx = -1;
for (int i = 0; i < vals.length ; i++) {
float v = vals[i];
if(v>=0 && (idx==-1 || v<vals[idx])) idx=i;
}
return idx;
}

static float[] removeMins(int n, float[] vals) { //Removes n minimums of the array and returns a new array without them;
while (n > 0) {
int a = indexOfMin(vals);
vals[a] = -1;
--n;
}
float[] res = new float[vals.length - n];
int b = 0;
for (int i = 0; i < vals.length; i++)
if (vals[i] != -1) {
res[b] = vals[i];
++b;
}
return res;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Number of Grades ? ");
float[] vals= new float[in.nextInt()];
for (int i = 0; i < vals.length ; i++) {
System.out.println("Grade "+ (i+1) +" ? ");
vals[i]=in.nextFloat(); //Line of the Error;
}
System.out.println("Number of Grades to the Average ? ");
int n = in.nextInt();
float [] best = removeMins(n,vals);
System.out.print("Best " +n+ " Grades: ");
for (int i = 0; i < best.length ; i++)
System.out.print(best[i]);
System.out.println("");
System.out.println("Average of the " +n+ " Best Grades = "+average(best));
}

}

编辑

我正在使用 Intellij

输入和完整错误消息:

年级数?

5

1级?

7.3

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:860)
at java.base/java.util.Scanner.next(Scanner.java:1497)
at java.base/java.util.Scanner.nextFloat(Scanner.java:2399)
at G2a.main(G2a.java:42)

进程已完成,退出代码为 1

最佳答案

我猜你在输入中使用了类似的东西:

1.5

请改用以下内容:

1,5

输入 float 。如果您使用点,解决方案可能是在 Scanner 中使用精确的区域设置。尝试将 main() 方法中的第一行更改为:

Scanner in = new Scanner(System.in);

至:

Scanner in = new Scanner(System.in).useLocale(Locale.US);

此行将精确显示您在输入十进制数字时要使用的表示法。看,它如何改变了输入的读取方式(现在点可以,而逗号不行):

Number of Grades ? 
3
Grade 1 ?
1.3
Grade 2 ?
1,4
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextFloat(Unknown Source)
at G2a.main(G2a.java:44)

关于java - 使用 nextFloat() 时线程 "main"java.util.InputMismatchException 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48244290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com