1

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 Answers3

0

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

NubDev
  • 506
  • 11
0

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

0

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.

Sercan
  • 2,081
  • 2
  • 10
  • 23
  • @user16320675 if you do not test for `>= 70`, then `40` will return as `C`. If you do not test `< 70`, then 90 will return as `D`. So, it is needed. – Sercan Jul 02 '23 at 17:36
  • @user16320675 you are right. But, this is an answer to OP's question (working version of OP's code), not the best solution. I would test the higher score `>= 90` first to avoid double-condition checks in each statement. – Sercan Jul 02 '23 at 18:04