Java Program to Read a Grade & Display the Equivalent Description
Problem Statement: Numbers on a scale of 1 to 100 are randomly given the grade as the input from the user and then match the input grade of the user against the given cases to generate the desired output.
Real life Example
Consider a number on a scale of 1 to 100 are written on a piece of paper slips. Now person starts picking slips one by one and starts organizing them in such a manner that he starts putting slips in 10 different boxes prior deciding making 10 different pots in such a manner slips numbering 1-10 in ‘pot A’, 11-20 in ‘pot B’ and so on till labeling and inserting slips till all the slips are organized in labeled pots. He did this in order to easily figure out numbers written on slips.
So in technical terms In these ways machine get
- Take input from the user
- Match the grade using equal to the operator (==)
- Generate the equivalent description as the output
There are several methods starting from brute force(naive) to most optimal. Few are discussed below :
- Using the If-Else Method
- Switch case Method
The grades are assigned using the following
Approach 1: If-Else Statement
Below is the implementation of the above approach
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
System.out.println(
"Enter Grade varying from S,A,B,C,D" );
String grade = "A" ;
if (grade == "S" ) {
System.out.println(
"Student has scored between 90 to 100" );
}
else if (grade == "A" ) {
System.out.println(
"Student has scored between 80 to 90" );
}
else if (grade == "B" ) {
System.out.println(
"Student has scored between 70 to 80" );
}
else if (grade == "C" ) {
System.out.println(
"Student has scored between 60 to 70" );
}
else if (grade == "D" ) {
System.out.println(
"Student has scored between 50 to 60" );
}
else {
System.out.println(
"The grade you entered is not valid!" );
}
}
}
|
Output
Enter Grade varying from S,A,B,C,D
Student has scored between 80 to 90
Approach 2: Switch Case
Below is the implementation of the above approach
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
String grade = "W" ;
switch (grade) {
case "S" :
System.out.println(
"Student has scored between 90 to 100" );
break ;
case "A" :
System.out.println(
"Student has scored between 80 to 90" );
break ;
case "B" :
System.out.println(
"Student has scored between 70 to 80" );
break ;
case "C" :
System.out.println(
"Student has scored between 60 to 70" );
break ;
case "D" :
System.out.println(
"Student has scored between 50 to 60" );
break ;
default :
System.out.println(
"The grade you entered is not valid!" );
}
}
}
|
Output
The grade you entered is not valid!
Time complexity: O(1) because constant operations are done
Auxiliary space: O(1)
Last Updated :
12 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...