How do I use the if-then-else statement?

Category: fundamental, viewed: 371 time(s).

The if-then-else control flow statement adds a secondary path to the if statement when the expression evaluates to false. When it evaluates to false the else block will be executed.

Below is the program that takes input of user test score and evaluates the score to get the corresponding grade.

package org.kodejava.example.lang;

import java.io.Console;

public class IfThenElseDemo {
    public static void main(String[] args) {
        //
        // Get an instance of system console for taking user
        // input.
        //
        Console c = System.console();

        int score = 0;
        String grade;

        System.out.print("Please enter your score: ");

        try {
            //
            // Take user score input and convert the input
            // value into number.
            //
            score = Integer.valueOf(c.readLine());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 60) {
            grade = "C";
        } else if (score >= 50) {
            grade = "D";
        } else {
            grade = "F";
        }

        System.out.println("Grade = " + grade);
    }
}

When the program executed you'll need to input the test score and the program will give you the grade.

Please enter your score: 75
Grade = C
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats