java programming

The following script will compute grade averages using java. Just copy and paste the below script into your preferred IDE (Integrated Development Environment) and run it.

 

/*
   	Date:		7/1/2018
	Program:	AveragingGradesApp.java
	Purpose:	This program will prompt the user to see how many grades will
        be entered.  Based on the user input, an array will be constructed, the average
        will be calculated, and the average and all grades entered will be displayed 
        after being formatted to 2 decimal places.  This program also uses validation 
        to ensure user input falls within specified criteria.
*/

//packages to import
import java.util.Scanner; //to get user input
import java.text.NumberFormat; //to format output

public class AveragingGradesApp
{
	public static void main(String[] args)
	{
		//declare and construct
		Scanner sc = new Scanner(System.in);
		NumberFormat number = NumberFormat.getNumberInstance();
		number.setMinimumFractionDigits(2);
		number.setMaximumFractionDigits(2);
      	float average;
      	int size = 0;
      	String choice = "y";

		//loop while user selects y or Y
      	while (choice.equalsIgnoreCase("Y"))
      	{
	//find out how many grades the user would like to enter
	size = getIntWithinRange(sc, "How many grades would you like to enter? ", 1, 10);
	System.out.println();

			//construct the grades array based on the size input from the user
			float grades[] = new float[size];

			//get grades input from the user
			grades = getGrades(sc, grades); //whenever pass array
			System.out.println();

			//calculate the average
			average = calculateAverage(grades);

			//display the output
			displayOutput(number, grades, average);

			//see if the user would like to continue
			choice = getValidString(sc, "Continue? (y/n): ", "y", "n");
		} //end while loop
	} //end main()

    //the getIntWithinRange() method will get int data from the user, validate
    private static int getIntWithinRange(Scanner sc, String prompt,
    int min, int max)
    {
        int i = 0;
        boolean isValid = false;
        while (isValid == false)
        {
            i = getInt(sc, prompt);
            if (i <= min)
                System.out.println("Error! Number must be greater than " + min + ".");
            else if (i > max)
                System.out.println("Error! Number must be " + max + " or less.");
            else
                isValid = true;
        } //end while loop

        //return valid data to the calling method
        return i;
    } //end getIntWithinRange(Scanner, String, int, int)

	//the getInt() method will get int data from the user, validate it
    private static int getInt(Scanner sc, String prompt)
    {
        int i = 0;
        boolean isValid = false;
        while (isValid == false)
        {
            System.out.print(prompt);
            if (sc.hasNextInt())
            {
                i = sc.nextInt();
                isValid = true;
            } //end if
            else
            {
                System.out.println("Error! Invalid number. Try again.");
            } //end else
            sc.nextLine();  // discard any other data entered on the line
        } //end while loop

        //return the valid data to the calling method
        return i;
    } //end getInt(Scanner, String)

	//the getGrades() method will call the appropriate methods to validate grade input
	private static float[] getGrades(Scanner sc, float grades[])
	{
		for(int i = 0; i < grades.length; i++)
		{
			grades [i] = getFloatWithinRange(sc, "Enter grade #" + (i + 1) + ": ", 0, 100);
		}//end for loop
		return grades;
	} //end getGrades()

    //the getFloatWithinRange() method will get float input from the user
    private static float getFloatWithinRange(Scanner sc, String prompt,
    float min, float max)
    {
        float f = 0.0F;
        boolean isValid = false;
        while (isValid == false)
        {
            f = getFloat(sc, prompt);
            if (f <= min)
                System.out.println("Error! Number must be greater than " + min + ".");
            else if (f > max)
                System.out.println("Error! Number must be " + max + " or less.");
            else
                isValid = true;
        } //end while loop

        //return the valid data back to the calling method
        return f;
    } //end getDoubleWithinRange(Scanner, String, double, double)

	//the getFloat() method will get float input from the user
    private static float getFloat(Scanner sc, String prompt)
    {
        float f = 0.0F;
        boolean isValid = false;
        while (isValid == false)
        {
            System.out.print(prompt);
            if (sc.hasNextFloat())
            {
                f = sc.nextFloat();
                isValid = true;
            } //end if
            else
            {
                System.out.println("Error! Invalid number. Try again.");
            } //end else
            sc.nextLine();  // discard any other data entered on the line
        } //end while loop

        //return the valid data back to the calling method
        return f;
    } //end getDouble(Scanner, String)

	//the calculateAverage() method calculates 
   	private static float calculateAverage(float[] grades)
   	{
		float sum = 0, average = 0;
		for(float grade : grades)
		{
			sum += grade; //can also be sum = sum + grade;

		}//end for loop... curly braces aren't necessary

		average = sum / grades.length;

		return average;
	} //end calculateAverage()

	//the displayOutput() method displays formatted grades and average
	private static void displayOutput(NumberFormat number, float[] grades, float average)
	{
		System.out.println("\nYou entered the following grades:");
		for(float grade : grades)
			System.out.println(number.format(grade)); 
		System.out.println("\nThe average grade is " + number.format(average));

	} //end displayOutput()

	//the getValidString determines if the entry is one of the valid choices
	private static String getValidString(Scanner sc, String prompt, String s1, String s2)
	{
		String s = "";
		boolean isValid = false;
		while (isValid == false)
		{
			System.out.print(prompt);
			s = sc.nextLine();
			if (s.equalsIgnoreCase(s1) || s.equalsIgnoreCase(s2))
			{
				isValid = true;
			} //end if
			else
			{
			System.out.println("Error! Please enter '" + s1 + "' or '" + s2 + "'.");
			} //end else
		} //end while loop
		return s;
	} //end getValidString()
} //end class