I have a problem with my scanner in the main method. I know that this topic has been addressed before, but everything I've tried doesn't solve my problem. I hope you can help me.
import java.utill.Scanner;
public class Main {
public static void main(String[] args) {
Scanner c = new Scanner(System.in);
Grades grade = new Grades(4, 2);
System.out.println("1 is finished");
System.out.println("2 is starting");
int n = c.nextInt();
System.out.println("2.1 is starting");
int gr;
for (int i = grade.getTotal(); i < grade.getTotal() + n; i++) {
gr = c.nextInt();
grade.setGrades(gr, i, grade.getTotal() + n);
}
System.out.println("2 is finished");
System.out.println();
System.out.println("3 is starting");
for (int i = 0; i < grade.getTotal(); i++) {
System.out.println(grade.getGrade(i));
}
System.out.println("3 is finished");
System.out.println();
c.close();
}
}
import java.util.Scanner;
public class Grades {
public Grades(int total, int totalCurriculum) {
Scanner sc = new Scanner(System.in);
setTotalCurriculum(totalCurriculum);
setTotal(total);
for (int i = 0; i < total; i++) {
this.grades[i] = sc.nextInt();
}
sc.close();
}
public void setGrades(int grade, int index, int total) {
this.grades[index] = grade;
if (index < total) {
setTotal(this.total + total);
}
}
public int getGrade(int nr) {
return grades[nr];
}
public int getLocalAverage(int nr) {
return localAverage[nr];
}
public float globalAverageCalc(int[] localAverage) {
int sum = 0;
for (int i = 0; i < getTotal(); i++) {
sum = sum + getGrade(i);
}
return (float) sum / getTotalCurriculum();
}
}
When i try to input the int value for int n
(under System.out.println("2 is starting");
) the error appears and the program stops.
This is the console output:
5
4
7
9
1 is finished
2 is starting
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:945)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at Test.Main.main(Main.java:22)
Process finished with exit code 1
Thank you for the help!