so I'm coding a small program to do the average of the best grades of a student, when I run it, I get this error Exception in thread "main" java.util.InputMismatchException.
I saw a post where it was said to use nextLine and then use parseInt ( in this case parseFloat) , but I'm not allowed to use that in here, so I'm looking for another opinion of what I could do.
Code:
import java.util.Scanner;
public class 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));
}
}
EDIT
I'm using Intellij
Input and full error message :
Number of Grades ?
5
Grade 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)
Process finished with exit code 1