Jump to content

6 posts in this topic

Recommended Posts

Posted

If & If-Else Statements 

 

An If Statement is a conditional statement. This basically means that if the program is allowed to execute a specific set of instructions, it will but, only if that condition is met. If that condition is not met the program skips over the instructions. 

An example of an If Statement is as followed:

 

public class Test {

   public static void main(String args[])
{
      int x = 15; \\initialzes an integer (x) to 15

      if( x < 20 ) {
         System.out.print("This is if statement"); \\this prints if x is less than 20
                
    			   }
                
 }
 }

 

An If-Else Statement works very similarly to an If Statement. The only major difference is that if your 'if' is NOT met it goes to 'else' and runs that code in the program. Instead of skipping over the conditional.

An example of an If-Else Statement is as followed:

public class Test {

   public static void main(String args[]) {
      int x = 30; \\like before, declares integer to a value. In this case 30

      if( x < 20 ) { //if x is less than 20 (it is not) it will run the if-clause
         System.out.print("This is if statement");
         }
         else{ // if the x is greater than 20 (in this situation) it runs the else-clause
         System.out.print("This is else statement");
      }
   }
}

 

 

Some very common errors in If  and If-Else Statements could be the following:

 

if (yourCondition); \\<< IF YOU PUT A SEMICOLON HERE IT ENDS THE STATEMENT WITHOUT READING THE ACTUAL STATEMENT
{
//code here
}

That code will result in an error!

 

 

-LifeElevated

  • Like 1
Posted
5 hours ago, LifeElevated said:

I did lol . Did you mean to say something different?

I mean you're showing if statements bases on one condition only so if{} else {} but you couls try putting

If

Else if

Else if

Else

 

So they understand they can use multiple conditions ;)

Posted
1 minute ago, Crypto said:

I mean you're showing if statements bases on one condition only so if{} else {} but you couls try putting

If

Else if

Else if

Else

 

So they understand they can use multiple conditions ;)

no u

Posted (edited)
On 5/15/2018 at 2:54 PM, Crypto said:

I mean you're showing if statements bases on one condition only so if{} else {} but you couls try putting

If

Else if

Else if

Else

 

So they understand they can use multiple conditions ;)

You could also put nested if's but those are more complex so I left them out.

if{

else{ 

if

}

}

if{}

 

Updated by LifeElevated
×
  • Create New...

Important Information

We would like to place cookies on your device to help make this website better. The website cannot give you the best user experience without cookies. You can accept or decline our cookies. You may also adjust your cookie settings. Privacy Policy - Guidelines