Java, how to use IF and ELSE: Testing and Controlling what will run

So far our codes were procedural. That is, following an order of execution: from beginning to the end, running everything.

But everything ran whenever we use a program?
Of course not, some yes, other not. We make choices.

That's what makes the if else, allows us to choose to do certain things.


Think in it meaning, from language.
The syntax is:

if ( condition ){
    If the condition is true
    this block of code is executed

And if it is not true?
Dont't run, simple.

We will test the condition '1 is equal to 2?', which obviously returns 'false', then test whether one is equal to one.
But it is in our language. How to ask this for the computer?

This way: if (1 == 2)
and then: if (1 == 1)

Look, is 1 == 2, not 1 = 2.
1 == 2 is a comparison, it is a question, it returns a logical value!
Here lies the key, if we can only put in if what returns logical value.

1 = 2 is simply an assignment of values!

Let codes:

public class Ifelse {
    public static void main(String[] args) {
        if (1 == 2){
            System.out.println("You will never read this, mwahuahuauha");
        if (1 == 1){
            System.out.println("1 equals 1? Really? ");


Again, just think in english.

What else comes from only if, and it only occurs when the if condition is false.
The syntax is as follows:

if (status) {
    If the condition is true
    this block of code is executed
} else {
    If the condition is false
    this block of code that will run

What else does not receive condition. It executes when the if not executed.

That is:
if (true)
   this happens
   this happens

Learn if else is not learning Java matters, is to learn all the other languages.
Incidentally, is learning logic. Is mathematics is reasoning.

This same rationale is used in extremely Engineering (Electrical, Electronic, Telecommunications) in Physics, Discrete Mathematics, all kinds of Science, in chips, Kernel Operating Systems, on airplanes and in everything that involve logic and digital world.

But let's do something useful:

Problem: Create a program that receives a notice (the Scanner class) and check if you got approved straight, if you have to a recovery exam or failed, and display this message:
The rule is as follows:
Note 7 or more, approved straight
Between 5 and 7: recovery test
Below 5: Direct disapproved.

It is important to try. Even if you can not get or only part of the problem.
That's how you evolve. Trying ... I already spent a few minutes in trouble, hours, days ... some others I did not even know where to start and ran to see the solution. Other night I wake at dawn with an idea how to solve one problema :)

At least think, and click here to see their full development.

No comments: