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

65 views Asked by At

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

3

There are 3 answers

2
Sercan On BEST ANSWER

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.

0
NubDev On

DO it using if/ else if. Like if(tscore >= 90), else if(tscore>=80) continue...

2
Matheus Brito On

The the ifs are inside each other, u just need separet with if-else-if

if(tscore >= 90){
  //do something
}else if(tscore >=80){
   //do another thing
 }else{
  //tae
 }

Class names in Java are capitalize more about