
|
Java Lesson 3: Ifs and Switches
- if ... else
if statements use the following syntax:
if (test)
{
statements;
}
else
{
other_statements;
}
- Boolean Tests
& Logical AND. Tests both conditions.
&& Conditional AND. If first condition
is false, will not evaluate the second condition.
| Logical OR. Tests both conditions.
|| Conditional OR. If first condition is true,
will not evaluate the second condition.
! NOT.
- Switch Statements
- Ternary Operator
- Sample Code:
public class LuckyNumber
{
public static void main(String[] args)
{
/* This script randomly selects a number from 1-100,
* prints out the number, identifies it as odd or even,
* then prints one of five messages.
*/
int num = (int)(100 * Math.random());
int quoteNum = (int)(num / 25);
System.out.println("Your lucky number is: " + num);
if (num%2 == 0)
System.out.println("This is an even number.");
else
System.out.println("This is an odd number.");
switch(quoteNum)
{
case 0:
System.out.println("May your dark days be few and far between.");
break;
case 1:
System.out.println("All that is worthy requires sacrifice.");
break;
case 2:
System.out.println("Enjoy the fruits of your work.");
break;
case 3:
System.out.println("May you excel in all things.");
break;
default:
System.out.println("You are truly blessed.");
}
}
}
- The Math.random() function generates a random number between
0 and 1.
- The random number has been explicitly cast as an integer by
placing (int) in front of the caluation.
Restricted access |