Conditionals(If Statement)

Overview

Conditional structures

The conditional statement we seen:

Syntax of the 'if' Statement Example Explanation

if ( condition ) 
   statement

OR

if ( condition ) {
   statement1;
   statement2;
   ...
}  
    
int x;
int max;


...


if (x > max) {
   max = x;
}  
  

A condition is a true/false expression.

If the condition is true, then the body of the if-statement is executed. Otherwise, it is not executed.

if(condition){         
    statement(s); 
 } 
else{        
    statement(s);  
}
int x;
int y;
int max;


...


if (x > y) {
   max = x;
}

else{
   max = y;
}

A condition is a true/false expression.

If the condition is true, then the body of the if-statement is executed. Otherwise, the statements in the body of the if-statement is executed.

 


Exercise

Statements
Description
if (value < 10) {
   value = 0; 
}
    

This is an "if" statement.

The type of the expression in parentheses is boolean. If num is less than 10 then the condition is true and the body of the if-statement, which is one statement (an assignment statement) will be executed. If the condition is false the assignment statement won't be executed. In this case, we don't know the value of num before the if statement is executed, so we can't tell if the body of the if statement will be executed.

The assignment statement assigns the value 0 to the variable num. We can infer that num is an integer (e.g. int) or a floating point number (e.g. double). If its type were boolean, the Java compiler would complain.

if ((choice == 'Y') || (choice == 'y')) {
    gameOver = true;
 }
else{
    gameOver = false;

}    
 
if (cost < amountInPocket) {
   System.out.println("Spending = $" + cost);
   amountInPocket = amountInPocket - cost;
 }
 
 

 


Exercise 2

Write a Java Program that determines whether the number entered by user is even or odd. The program must also let user know the result. E.g. 2 is even number.

Note: That for user input you need to use the functionality in TextIO.jar.


Exercise 3

A user enters some number x. Write a java program that does the following with input:

       - negative: change x to its absolute value (e.g. -5 to 5)and print its new value
       - in the range of 1 to 10: double the value of x and print it new value
       - greater than 10: print its value, double it, print its new value
       - for any other cases, do nothing

-->