javanested-if

is it possible to print only one statement in this nested if code?-Java


Our professor asked us to create a code that prints what grade you should be getting for a particular score, in a nested if code in Java

import java.util.Scanner;
public class nestedif {
    public static void main(String []args){
        Scanner sc = new Scanner(System.in);
        int tscore = sc.nextInt();

        if (tscore >=60){
            System.out.println("D");
            if (tscore >=70){
                System.out.println("C");
                if (tscore >=80){
                    System.out.println("B");
                    if (tscore >=90){
                        System.out.println("A");
                    }
                }
            }

        }
        else {
            System.out.println("tae");
        }
    }
}

it prints the grade but it also includes the first if's statement ex input: 90 output: A B C D


Solution

  • Your code prints multiple grades at the same time because when you enter 90, the condition is true for multiple if conditions. Not only you need to use else if, but also you need to specify the ranges for the grades as in tscore >= 60 && tscore < 70. So, your code should look like below;

    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int tscore = sc.nextInt();
    
        if (tscore >= 60 && tscore < 70) {
            System.out.println("D");
        } else if (tscore >= 70 && tscore < 80) {
            System.out.println("C");
        } else if (tscore >= 80 && tscore < 90) {
            System.out.println("B");
        } else if (tscore >= 90) {
            System.out.println("A");
        } else {
            System.out.println("tae");
        }
    }
    

    I would probably execute my code in debug mode to see the behaviour.