This is example code of a simple grade calculation. I don't understand how we are able to take multiple inputs when there isn't a scanner directly in the next line.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avg;
String[] name = new String[10]; //craeting a string array named "name" that has 10
for (int j = 0; j<10; j )
{
System.out.println("What is the name of the student?");
name[j] = sc.nextLine(); // nextLine because we want the string of the input
System.out.println("What are their test scores?");
avg = calculateAverage(j);
System.out.println("Their average is " avg ", that is a " calculateGrade(avg));
}
}
public static double calculateAverage(int j) {
double [][]gradebook = new double[10][5];
Scanner sc = new Scanner(System.in);
double sum = 0;
for (int v=0; v<5; v )
{
gradebook[j][v] = sc.nextDouble();
sum = gradebook[j][v] sum;
}
double avg = sum / 5;
return avg;
}
public static String calculateGrade (double avg)
{
if (avg >= 90 && avg <= 100) {
return "A";
}
else if (avg >= 80) {
return "B";
}
else if (avg >= 70) {
return "C";
}
else if (avg >= 60) {
return "D";
}
else {
return "F";
}
}
}
I know that there's a scanner in calculateAverage, but what makes it possible for a user to respond with multiple numbers and those inputs being pushed into calculateAverage? Shouldn't there be a scanner in main that directly records the inputs? Are the inputs somehow being directly pushed into calculateAverage?
CodePudding user response:
The scanner in calculate average reads in numbers from gradebook[j][v] = sc.nextDouble();
whenever this line is reached the code will stop and wait for input.
After input, the loop continues and asks for another number as input.