Use of booleans in java

Part A: Walk in the park
Eastside High assigns letter grades as follows.
Numeric Score Letter grade
93 or above A
From 84 to 92 inclusive B
From 75 to 83 inclusive C
From 50 to 74 inclusive D
Below 50 F
Write a Java application, called Grade.java, to read a student’s numeric score from the keyboard and
displays the letter grade earned. For example, if the score is 65, your program should display something
similar to:
Numeric Score : 65
Letter Grade : D

//My code below

import java.util.Scanner;

public class Grade
{
    public static void main(String[] args)
    {
        Scanner in  = new Scanner(System.in);
        
        int Grade ;
        int x = in.nextInt(); //Reads input
        System.out.print("Grade :");

        if(x>=93)
        {
            System.out.print("A");
        }

        if(x>=83)
        {
            System.out.print("B");
        }

        if(83>=x)
        {
            System.out.print("C");
        }

        if(74>=x)
        {
            System.out.print("D");
        }

        if(x<=49){
            System.out.print("F");
        }

        in.close();


    }
}

But everytime I execute a value below 83, it prints multiple letters.How do I fix it so it gives out one letter for each input value?

Let’s take a journey through your main function. Let’s say x equals 10. We get to the first if statement and x is not greater than/equal to 93 and thus ‘A’ is not printed. We get to the next if statement and x is not greater than/equal to 83 and thus B is not printed. Then we get to the third if statement and x is less than/equal to 83 and thus C is printed. Then we get to the fourth if statement and x is less than/equal to 74 and thus D is printed. Do you see why multiple letters are being printed out?

Same thing happens when x equals 95. The first if will print A because x is greater than/equal to 93. Then the second if will print B because x is greater than equal to 83. You want to use a decision tree structure that will only execute once. Do you have any ideas on how to do this?

Also, I would recommend that you use the same type of comparison all the way through. You start off using greater than/equal for the first two comparisons and then switch to less than/equal for the last three. Pick one and stick with it.

3 Likes

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).