Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The below Java progam inputs an integer grade and outputs a letter grade. If-els

ID: 3881773 • Letter: T

Question

The below Java progam inputs an integer grade and outputs a letter grade. If-else-if statements are used below instead of if statements alone.

In one to two paragraphs explain with detailed points on why it is better to use if-else-if instead if just if statements in the below code.

import java.util.Scanner;

public class GradeLetterTest {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter the three different inputs:");

String s = "";

char c ;

int grade = scan.nextInt();

if(grade<0 || grade > 100) {

s ="ERROR You have entered an invalid input";

System.out.println(s);

} else {

if(grade>=90) {

c = 'A';

} else if(grade>=80 && grade<90) {

c = 'B';

} else if(grade>=70 && grade<80) {

c = 'C';

} else if(grade>=60 && grade<70) {

c = 'D';

} else {

c='F';

}

System.out.printf("You have earned the letter grade: %c ",c);

}

}

}

Explanation / Answer

if else is better because if one case fails then go to else part. if we not use if-else, and only use if then it compares every time in execution for all if condition.
it's best practice to use if-elseif-else anyhow. Suppose you change your code such that you don't do a return in every if block. Then, to remain efficient, you'd also have to change to an if-elseif-else idiom.

Code with a comment.

import java.util.Scanner;

public class GradeLetterTest {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter the three different inputs:");

String s = "";

char c ;

//take grade input

int grade = scan.nextInt();

//if statement for comparision between greater then 0 and less than 100 otherwise give error

if(grade<0 || grade > 100) {

s ="ERROR You have entered an invalid input";

System.out.println(s);

} else {

//if grade if greater than 90 print grade A

if(grade>=90) {

c = 'A';

} //if grade if greater than 80 and less than 90 print grade B

else if(grade>=80 && grade<90) {

c = 'B';

} //if grade if greater than 70 and less than 80 print grade B

else if(grade>=70 && grade<80) {

c = 'C';

} //if grade if greater than 60 and less than 70 print grade B

else if(grade>=60 && grade<70) {

c = 'D';

} // else print fail

else

{

c='F';

}

System.out.printf("You have earned the letter grade: %c ",c);

}

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote