Coby Bushong - 1 year ago 155
Java Question

# Else-if statement

So I have my code working to tell me what the grade is for the average, however, what I need it to actually do is tell me what the grade is for each individual grade itself, example user enters for test1 80, I need it to say that the grade is a B and so on. This is what I have so far. Im not sure if I can even put multiple variables into 1 if else statement or not, or if Ill have to have 5 different else if statements.

``````import java.util.Scanner;           //user input
import java.text.DecimalFormat;     //formats decimal places

/*This program is made to recieve 5 test grade inputs from the
user and then calculate their average and return their grade.
*/
public class Lab
{
public static void main(String[] args)
{
//place holders for test scores
double test1,test2,test3,test4,test5;

System.out.println("Enter 5 of your test grades: ");

//create scanner for user imput
Scanner keyboard = new Scanner(System.in);
test1 = keyboard.nextDouble();
test2 = keyboard.nextDouble();
test3 = keyboard.nextDouble();
test4 = keyboard.nextDouble();
test5 = keyboard.nextDouble();
keyboard.nextLine();

//calls method 1
double average = calcAverage(test1, test2, test3, test4, test5);

//calls method 2

//formats how the average will be displayed
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("The average is: " + df.format(average));
System.exit(0);
}

/*
The calcAverage method takes the test inputs from the
user and divides them by 5 getting the average of all 5.
*/

public static double calcAverage(double test1, double test2, double test3, double test4, double test5)
{
double average = (test1 + test2 + test3 + test4 + test5) / 5;
return average;
}

/*
The getGrade method will take what was produced in the calcAverage method
and find out where the average falls, thus giving the user his/her grade.
*/

public static void getGrade(double average)
{
if (average>90)
{
System.out.println("You have an A");
}
else if (average>=80)
{
System.out.println("You have a B");
}
else if (average>=70)
{
System.out.println("You have a C");
}
else if (average>=60)
{
System.out.println("You have a D");
}
else if (average<60)
{
System.out.println("You have a F");
}
}
}
``````

Your `getGrade()` should probably return the grade. Something like,

``````public static String getGrade(double average)
{
if (average>90)
{
return "A";
}
else if (average>=80)
{
return "B";
}
else if (average>=70)
{
return "C";
}
else if (average>=60)
{
return "D";
}
else
{
return "F";
}
}
``````

Then you call it for an individual test (or the average) -

``````System.out.printf("You got a %s on test1.", getGrade(test1));
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download