Search This Blog

Sunday, July 19, 2020

Code Blocks, if else

Code Blocks:

     Use of code block is optional if you have got only one statement you want to process.

Note: Variable inside a block is called scope.  scope really deals with accessibility of variables in certain situation or, places in a code block.

program:


public class CodeBlocks_IfBlock {
public static void main(String[] args) {

int myScore = 300;
if (myScore == 500) // code block is not added { }
System.out.println("Your score is 500");
System.out.println("Next line Added to test");
if (myScore == 300) {
System.out.println(" Your score is 300");
}else {
System.out.println(" Else Block ...");
}
}

}


Challenge:
Solution:


public class ChallangeSol {
public static void main(String[] args) {

boolean newameover = true;
int score = 10000;
int levelCompleted = 8;
int bonus = 200;
if (newameover) {
int finalScore = score + (levelCompleted * bonus);
System.out.println("Your final bonus = " + finalScore);
}
}
}


if else 
 The if statement  identifies which statement or, block to be run based on the value of an expression  . In other words based on a specific condition.

     Inside the code block defined by curly braces { and } we can have one or multiple statements. We can use else statement after the if  . In that case the condition is false the else block will be executed.

We can also add else if  to test multiple conditions.

if and else  structure:

if(condition)
 {
//if statement (block )
} else{
  //else statement (block)
}






No comments:

Post a Comment