Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How are these inputs being recorded and passed to the method?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading