How to Re prompt a User Again in if Else Java

Till now, nosotros take learned about press something on screen, taking input from a user, dissimilar data types and operators. These were all the nuts of Java, From this affiliate onwards, we will look into more than programmatic concepts of Java.

Many times, we demand to check a condition to brand a decision. For instance, if it is raining, we will take an umbrella, otherwise not. Similarly, if a number is divisible by ii, it is even, otherwise, it is odd.

If else in Java

Such types of decisions are made in Java using if...else.


Java if Statement

Again have the example of raining. If it is raining, a person will take an umbrella. This type of decision making is washed using an if statement.

Let's have a look at the syntax of an if statement before looking at examples.

Java if Syntax

                        if            (            condition            )            {            statements            }          

First, if(condition) is written, where the condition written inside parentheses ( ) is what affects the decision to be made.

The statements written within the braces { } following if(condition) constitute the body of if.

If the condition is true, then the statements within the torso of if are executed, otherwise they are not executed.

Coffee if Examples

Let'due south meet an case.

                                class                Test                {                public                static                void                master                (                Cord                []                args                )                {                int                num1                =                10                ,                num2                =                20                ;                if                (                num1                <                num2                )                {                Arrangement                .                out                .                println                (                "num2 is greater than num1"                );                }                }                }              

Output

num2 is greater than num1

Here, the condition of if is num1 < num2.

The body of if contains the statement System.out.println("num2 is greater than num1"). This argument will become executed but if the condition of if is true.

Since the values of the variables num1 and num2 are 10 and twenty respectively, the status num1 < num2 became true and thus the statement in the trunk of if got executed and "num2 is greater than num1" got printed.

If the value of num1 was more than num2, and so the status of if would have become false and the statement in its body would not have executed.

Try this instance yourself.

It is a good practice to add indentation earlier the statements within the torso of if.

That was easy, right?

Look at another instance.

                                class                Test                {                public                static                void                principal                (                String                []                args                )                {                int                num1                =                x                ,                num2                =                20                ;                if                (                num1                <                num2                )                {                Arrangement                .                out                .                println                (                "num2 is greater than num1"                );                }                System                .                out                .                println                (                "This statement is outside the body of if"                );                }                }              

Output

num2 is greater than num1
This statement is outside the body of if

In this example, nosotros added a statement outside the trunk of if. Thus, this statement System.out.println("This argument is outside the trunk of if") will always go executed irrespective of whether the condition of if is true or simulated.

Allow's come across 1 more example.

                                import                coffee.util.Scanner                ;                class                Examination                {                public                static                void                main                (                String                []                args                )                {                Organization                .                out                .                println                (                "Enter your age"                );                Scanner                south                =                new                Scanner                (                Organization                .                in                );                int                historic period                =                s                .                nextInt                ();                if                (                historic period                >                eighteen                )                {                Arrangement                .                out                .                println                (                "Your age is 18+"                );                System                .                out                .                println                (                "You are eligible to vote"                );                }                Organization                .                out                .                println                (                "This argument is outside the body of if"                );                }                }              

Output

Enter your age xx
Your age is 18+
You lot are eligible to vote
This statement is outside the body of if

Hither, the condition of if is historic period > 18.

The body of if consists of the statements System.out.println("Your historic period is 18+") and System.out.println("Yous are eligible to vote").

In the program, we are assigning the age entered by the user to a variable age. Since the age entered past the user is 20, the condition age > 18 became true and the statements inside the torso of if got executed.

If the body of if or else consists of only i statement, then the braces { } enclosing the body can be omitted. (We will learn almost else in the next section)

first statement of if in Java

If there is just one statement in the body of if, and so it is non mandatory to put the braces { } to enclose the body. For example, in the first and 2d programs we saw in this chapter, the torso of if can be written without beingness enclosed inside { } as shown below.

                                class                Test                {                public                static                void                main                (                Cord                []                args                )                {                int                num1                =                10                ,                num2                =                20                ;                if                (                num1                <                num2                )                Organisation                .                out                .                println                (                "num2 is greater than num1"                );                Organisation                .                out                .                println                (                "This statement is outside the trunk of if"                );                }                }              

Output

num2 is greater than num1
This statement is outside the body of if

In the above case, since we have not written braces { } for marking the body of if, the beginning statement written later the if(num1 < num2), i.due east. System.out.println("num2 is greater than num1") is considered every bit the body of if.

Numbers like ane, 1.ii, 3, etc except 0 are also evaluated equally true if used as a condition. 0 is evaluated every bit false.

Let'due south wait at i more example.

                                course                Test                {                public                static                void                main                (                String                []                args                )                {                if                (                truthful                )                System                .                out                .                println                (                "This will ever execute!"                );                }                }              

Output

This will always execute!

We accept directly written true for the condition. Hence, the condition is always true and the statement inside if - Organization.out.println("This will always execute!"); is always executed.

Then, it was this piece of cake to check a status and perform a chore or print something if that condition is true. Wait, there is more that we can do past checking conditions. Let'south wait at that in the next sections.


Java if...else Statement

Now, consider the same example of raining. If it is raining, a person will take an umbrella, otherwise the person will wear a hat. Such decision making in which if the condition is true, and then we perform some action, and if the condition is false, and so we perform some other activity is washed using an if...else argument.

Let'southward wait at the syntax of an if...else statement.

Coffee if...else Syntax

                        if            (            condition            )            {            statements            }            else            {            statements            }          

The statements written inside the braces { } following if(condition) plant the body of if.

The statements written inside the braces { } following else constitute the body of else.

If the condition is true, and then the statements inside the body of if are executed, otherwise the statements inside the body of else are executed.

Java if...else Examples

Permit's see an instance.

                                grade                Exam                {                public                static                void                master                (                Cord                []                args                )                {                int                num1                =                20                ,                num2                =                10                ;                if                (                num1                <                num2                )                {                Organization                .                out                .                println                (                "num2 is greater than num1"                );                }                else                {                Organization                .                out                .                println                (                "num2 is less than num1"                );                }                System                .                out                .                println                (                "This statement is outside the torso of if and else"                );                }                }              

Output

num2 is less than num1
This statement is outside the trunk of if and else

Since num1 is greater than num2, the condition num1 < num2 became false, and hence the argument in the body of else got executed.

If the condition was truthful, so the statement in the body of if would have got executed resulting in the following output.

num2 is greater than num1 This statement is exterior the trunk of if and else          

Look at some other case.

                                import                java.util.Scanner                ;                class                Test                {                public                static                void                main                (                String                []                args                )                {                System                .                out                .                println                (                "Enter your age"                );                Scanner                southward                =                new                Scanner                (                System                .                in                );                int                age                =                south                .                nextInt                ();                if                (                age                >                xviii                )                {                System                .                out                .                println                (                "Your age is eighteen+"                );                Arrangement                .                out                .                println                (                "You lot are eligible to vote"                );                }                else                {                System                .                out                .                println                (                "Your age is not 18+"                );                System                .                out                .                println                (                "You are not eligible to vote"                );                }                }                }              

Output

Enter your historic period 15
Your historic period is not 18+
You are not eligible to vote

Since the historic period entered by the user is 15, the condition age > 18 became simulated and the statements within the body of else got executed.

At present let'south write a plan to check if a number is fifty-fifty or odd.

                            course              Test              {              public              static              void              chief              (              String              []              args              )              {              int              num              =              12              ;              if              (              num              %              2              ==              0              )              {              System              .              out              .              println              (              "Number is even"              );              }              else              {              Organization              .              out              .              println              (              "Number is odd"              );              }              }              }            

Output

In the status num % ii == 0, we are checking if the rest obtained by dividing num by ii is 0. If it is 0 (num is perfectly divisible by 2), so the torso of if gets executed, otherwise the trunk of else gets executed. In this program, the value of num is 12, hence the condition became true and the body of if got executed.

Since the body of if and else in the higher up example contains simply one argument each, so nosotros can remove the braces { } enclosing the torso as shown beneath.

                            class              Test              {              public              static              void              principal              (              String              []              args              )              {              int              num              =              12              ;              if              (              num              %              two              ==              0              )              System              .              out              .              println              (              "Number is fifty-fifty"              );              else              System              .              out              .              println              (              "Number is odd"              );              }              }            

Output


Java else if Statement

Many times we autumn in situations when merely if and else are not sufficient. For example, if y'all have 5 rupees, then you volition buy a candy, if yous have 10 rupees, then a chocolate and if more than 100, then a cake. Java provides another tool else if to get this done.

Permit's wait at its syntax.

Coffee else if Syntax

                        if            (            condition            )            {            statements            }            else            if            (            condition            )            {            statements            }            else            if            (            status            )            {            statements            }            ...            ...            else            {            statements            }          

First, the condition of if is checked. If it is true, so the trunk of if is executed.

If the condition of if is faux, then the condition of the kickoff else if is checked. If the condition of the first else if is true, then its body is executed, otherwise the condition of the next else if is checked.

If the conditions of if and all the else if blocks are faux, then the body of the else is executed.

Java else if Examples

Await at the following case.

                                import                coffee.util.*                ;                class                Examination                {                public                static                void                primary                (                String                []                args                )                {                int                x                ,                y                ,                z                ;                Scanner                s                =                new                Scanner                (                System                .                in                );                Organisation                .                out                .                println                (                "Enter first number"                );                x                =                s                .                nextInt                ();                System                .                out                .                println                (                "Enter second number"                );                y                =                southward                .                nextInt                ();                Organisation                .                out                .                println                (                "Enter 3rd number"                );                z                =                s                .                nextInt                ();                if                ((                10                >                y                )                &&                (                x                >                z                ))                {                Arrangement                .                out                .                println                (                x                +                " is the greatest integer"                );                }                else                if                ((                y                >                x                )                &&                (                y                >                z                ))                {                Organization                .                out                .                println                (                y                +                " is the greatest integer"                );                }                else                System                .                out                .                println                (                z                +                " is the greatest integer"                );                }                }              

Output

Enter commencement number
4
Enter 2d number
five
Enter third number
one
five is the greatest integer

Kickoff, the condition of if is checked. If it is imitation, then the status of else if is checked and if that is likewise fake, so the torso of else is executed.

In the above example, we are given 3 numbers ten, y and z and nosotros have to notice the greatest among them. For that, first nosotros will compare the first number with the other numbers i.e. 10 with both y and z. If the condition (x>y && ten>z) of if is true (if both are truthful, means x is the greatest), then the trunk of if is executed.

If not, then the condition (y>ten && y>z) of else if is checked. If this condition is true, then the trunk of else if will be executed. If this is as well imitation, so the body of else will be executed.

In our case, since x is greater than y and z, therefore the condition of if became truthful and its body got executed.

Allow's see ane more example.

                            grade              Test              {              public              static              void              master              (              String              []              args              )              {              char              class              =              'A'              ;              if              (              form              ==              'A'              )              {              Arrangement              .              out              .              println              (              "First-class !"              );              }              else              if              (              class              ==              'B'              )              {              System              .              out              .              println              (              "Outstanding !"              );              }              else              if              (              form              ==              'C'              )              {              System              .              out              .              println              (              "Good !"              );              }              else              if              (              grade              ==              'D'              )              {              System              .              out              .              println              (              "Can do ameliorate"              );              }              else              if              (              grade              ==              'E'              )              {              System              .              out              .              println              (              "But passed"              );              }              else              if              (              form              ==              'F'              )              {              System              .              out              .              println              (              "You failed"              );              }              else              {              System              .              out              .              println              (              "Invalid grade"              );              }              }              }            

Output

First the condition of if is checked. If it is truthful, then only statements in the body of if are executed, otherwise the status of the outset else if is checked. If information technology is true, then its body is executed, otherwise the status of the next else if is checked. If none of them are true, then the body of else is executed.

Java Nested if...else Statements

We can utilize if, if...else or if...else if...else statements within the body of other if, if...else or if...else if...else statements. This is called nesting.

Let's see an example.

                            class              Test              {              public              static              void              main              (              String              []              args              )              {              int              rating              =              8              ;              if              (              rating              <              5              )              {              System              .              out              .              println              (              "Bad rating"              );              }              else              {              if              (              rating              <              8              )              {              Organisation              .              out              .              println              (              "Boilerplate rating"              );              }              else              {              System              .              out              .              println              (              "Proficient rating"              );              }              }              }              }            

Output

Suppose the rating for a product can be from i to x. If the rating is less than five, then information technology is considered a Bad rating. Otherwise, if the rating is from 5 to seven then it is an Boilerplate rating, and if the rating is from viii to x then it is a Good rating.

Nested if else in Java

Here, we assigned the value 8 to the variable rating. In if...else, the condition rating < five of the outer if is checked. Since the condition is false, the statements inside the torso of the outer else are executed.

The following statements are inside the trunk of the outer else.

                        if            (            rating            <            8            )            {            System            .            out            .            println            (            "Average rating"            );            }            else            {            Organization            .            out            .            println            (            "Good rating"            );            }          

The showtime statement i.e., if(rating < eight) got executed kickoff. Since its condition rating < viii is false, the statement System.out.println("Skilful rating") inside the trunk of the inner else got executed.

Now expect at some other instance. The following plan checks whether a number is the greatest among iii numbers.

                                grade                Test                {                public                static                void                master                (                String                []                args                )                {                int                x                =                5                ,                y                =                2                ,                z                =                viii                ;                if                (                ten                >                y                )                {                if                (                x                >                z                )                Arrangement                .                out                .                println                (                "x is the greatest integer"                );                else                System                .                out                .                println                (                "10 is not the greatest integer"                );                }                else                Organisation                .                out                .                println                (                "x is not the greatest integer"                );                }                }              

Output

ten is not the greatest integer

Nested

Here, the following if...else statement is within if(10 > y).

                        if            (            10            >            z            )            System            .            out            .            println            (            "x is the greatest integer"            );            else            System            .            out            .            println            (            "x is not the greatest integer"            );          

Since the condition x > y of the outer if is true, the statements within the body of if got executed. Within the body of if, the first statement i.due east., if(x > z) got executed first. Since its status x > z is false, the statement System.out.println("x is not the greatest number.") in the body of the inner else got executed.

We can also do the same by using the && operator.

                                class                Exam                {                public                static                void                main                (                String                []                args                ){                int                10                =                5                ,                y                =                2                ,                z                =                viii                ;                if                (                (                ten                >                y                )                &&                (                10                >                z                )                ){                Organisation                .                out                .                println                (                "x is the greatest integer"                );                }                else                Organisation                .                out                .                println                (                "x is not the greatest integer"                );                }                }              

Output

ten is not the greatest integer

Hither, the expression within if is true only if both (x > y) and (x > z) are true. If that is the case, so x will exist the greatest number, otherwise not.


Java Ternary Operator

Ternary operator checks a status and then returns a value depending on whether the condition is true or false.

Expect at the following statements.

int num = x

String event = (num == 10) ? "num is equal to 10" : "num is non equal to ten";

In the second argument, ? : is a ternary operator. Information technology takes iii operands - num == x, "num is equal to x" and "num is non equal to 10".

The first operand is e'er a condition. If this condition is true, then the second operand is returned, otherwise the third operand is returned.

In our case, the condition num == x is checked. If this status is truthful, and then "num is equal to 10" is assigned to the variable result, otherwise "num is non equal to 10" is assigned to result. Since the value of num is ten, the value of outcome becomes "num is equal to 10".

Allow's generalize the syntax of the ternary operator.

Coffee Ternary Operator Syntax

condition ? value1 : value2

The status is checked outset. If information technology is truthful, and then value1 is returned, and if it is false, then value2 is returned.

ternary operator in Java

Coffee Ternary Operator Examples

Now await at the following instance.

                            grade              Test              {              public              static              void              master              (              String              []              args              ){              int              age              =              20              ;              String              message              =              (              age              >              18              )              ?              "You are eligible to vote"              :              "You are non eligible to vote"              ;              System              .              out              .              println              (              message              );              }              }            

Output

In this example, the condition historic period > 18 is true. Hence, the value "Y'all are eligible to vote" is assigned to the variable message.

If the condition age > eighteen was false, then the value "Y'all are not eligible to vote" would take been assigned to message and the output would be equally shown below.

You are not eligible to vote

Look at some other case which prints the maximum amongst two numbers.

                            grade              Exam              {              public              static              void              master              (              String              []              args              ){              int              num1              =              10              ,              num2              =              20              ;              int              max              =              (              num1              >              num2              )              ?              num1              :              num2              ;              System              .              out              .              println              (              "The greater number is "              +              max              );              }              }            

Output

Hither, the condition num1 > num2 is fake and hence num2 is assigned to the variable max.

Notation that both the examples discussed higher up tin can exist written using if..else as well. Using a ternary operator shortened the lawmaking.

Now let's wait at a more advanced example. The following plan prints the maximum among three numbers.

                                class                Test                {                public                static                void                main                (                String                []                args                ){                int                num1                =                x                ,                num2                =                xx                ,                num3                =                thirty                ;                int                max                =                ((                num1                >                num2                )                &&                (                num1                >                num3                ))                ?                num1                :                ((                num2                >                num3                )                ?                num2                :                num3                );                System                .                out                .                println                (                "The greatest number is "                +                max                );                }                }              

Output

The greatest number is 30

This is an example of a nested ternary operator. Try to understand the code yourself before looking at the explanation.

Nested ternary operator in Java

We are given three numbers num1, num2 and num3 and nosotros have to assign the greatest number amongst them to the variable max.

First, the condition (num1 > num2) && (num1 > num3) is checked. If this condition is true (which ways num1 is the greatest number) (greater than num2 and num3 both), then num1 is assigned to max.

However, if this condition is false (which means num1 is not the greatest number), then the expression (num2 > num3) ? num2 : num3 is evaluated and assigned to max. In this expression, the condition num2 > num3 is checked. If this condition is true (which means num2 is the greatest), then num2 is assigned to max, else num3 is assigned to max.

The equivalent if/else lawmaking for the aforementioned example would be:

                                form                Examination                {                public                static                void                chief                (                String                []                args                ){                int                num1                =                ten                ,                num2                =                20                ,                num3                =                xxx                ;                int                max                ;                if                ((                num1                >                num2                )                &&                (                num1                >                num3                ))                {                max                =                num1                ;                }                else                {                if                (                num2                >                num3                )                max                =                num2                ;                else                max                =                num3                ;                }                System                .                out                .                println                (                "The greatest number is "                +                max                );                }                }              

Output

The greatest number is 30

Using nested ternary operators instead of if...else is not recommended because information technology increases the complexity of the code.

In this chapter, yous learned about different ways y'all can perform some job based on some condition. Though yous saw different examples explaining the concept, it is necessary that you practice questions because it is a new concept. In the next chapter, nosotros volition look at another approach to perform decision making which can reduce the complexity of code as compared to if...else in some cases.

If something is important enough, fifty-fifty if the odds are stacked against you lot, yous should withal do it.

- Elon Musk


pollackalownd.blogspot.com

Source: https://www.codesdope.com/course/java-if-and-else/

0 Response to "How to Re prompt a User Again in if Else Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel