[go: up one dir, main page]

0% found this document useful (0 votes)
26 views12 pages

Nested If: JAVA For Beginners

The document provides explanations and examples of various Java programming concepts including: 1) Nested if statements and how else clauses are associated with the nearest if statement. 2) The if-else-if conditional structure and how conditions are evaluated from top to bottom. 3) The ternary operator (?:) that allows conditional assignment in a single line. 4) The switch statement for multi-way branching and how cases are executed until a break or the end is reached.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views12 pages

Nested If: JAVA For Beginners

The document provides explanations and examples of various Java programming concepts including: 1) Nested if statements and how else clauses are associated with the nearest if statement. 2) The if-else-if conditional structure and how conditions are evaluated from top to bottom. 3) The ternary operator (?:) that allows conditional assignment in a single line. 4) The switch statement for multi-way branching and how cases are executed until a break or the end is reached.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

JAVA for Beginners

Nested if
The main thing to remember about nested ifs in Java is that an else statement always refers to the
nearest if statement that is within the same block as the else and not already associated with an
else. Here is an example:

if(i == 10) {

if(j < 20) a = b;

if(k > 100) c = d;

else a = c; // this else refers to if(k > 100)

else a = d; // this else refers to if(i == 10)

Guessing Game v.3

// Guess the letter game, 3rd version.

class Guess3 {

public static void main(String args[])

throws java.io.IOException {

char ch, answer = 'K';

System.out.println("I'm thinking of a letter between A


and Z.");

System.out.print("Can you guess it: ");

ch = (char) System.in.read(); // get a char

if(ch == answer) System.out.println("** Right **");

else {

System.out.print("...Sorry, you're ");

// a nested if

if(ch < answer) System.out.println("too low");

else System.out.println("too high");

Riccardo Flask 37 | P a g e
JAVA for Beginners

A sample run is shown here:

I'm thinking of a letter between A and Z.

Can you guess it: Z

...Sorry, you're too high

if-else-if Ladder

if(condition)

statement;

else if(condition)

statement;

else if(condition)

statement;

...

else

statement;

The conditional expressions are evaluated from the top downward. As soon as a true condition is
found, the statement associated with it is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, the final else statement will be executed. The final else often acts as a default
condition; that is, if all other conditional tests fail, the last else statement is performed. If there is no
final else and all other conditions are false, no action will take place.

// Demonstrate an if-else-if ladder.

class Ladder {

public static void main(String args[]) {

int x;

for(x=0; x<6; x++) {

if(x==1)

System.out.println("x is one");

else if(x==2)

System.out.println("x is two");

Riccardo Flask 38 | P a g e
JAVA for Beginners

else if(x==3)

System.out.println("x is three");

else if(x==4)

System.out.println("x is four");

else

System.out.println("x is not between 1 and 4");

The program produces the following output:

x is not between 1 and 4

x is one

x is two

x is three

x is four

x is not between 1 and 4

Ternary (?) Operator

Declared as follows:

Exp1 ? Exp2 : Exp3;

Exp1 would be a boolean expression, and Exp2 and Exp3 are expressions of any type other than
void. The type of Exp2 and Exp3 must be the same, though. Notice the use and placement of the
colon. Consider this example, which assigns absval the absolute value of val:

absval = val < 0 ? -val : val; // get absolute value of val

Here, absval will be assigned the value of val if val is zero or greater. If val is negative, then absval
will be assigned the negative of that value (which yields a positive value).

Riccardo Flask 39 | P a g e
JAVA for Beginners

The same code written using the if-else structure would look like this:

if(val < 0) absval = -val;


else absval = val;

e.g. 2 This program divides two numbers, but will not allow a division by zero.

// Prevent a division by zero using the ?.


class NoZeroDiv {
public static void main(String args[]) {
int result;
for(int i = -5; i < 6; i++) {
result = i != 0 ? 100 / i : 0;
if(i != 0)
System.out.println("100 / " + i + " is " + result);
}
}
}

The output from the program is shown here:

100 / -5 is -20
100 / -4 is -25
100 / -3 is -33
100 / -2 is -50
100 / -1 is -100
100 / 1 is 100
100 / 2 is 50
100 / 3 is 33
100 / 4 is 25
100 / 5 is 20

Please note:

result = i != 0 ? 100 / i : 0;

result is assigned the outcome of the division of 100 by i. However, this division takes place only if i
is not zero. When i is zero, a placeholder value of zero is assigned to result. Here is the preceding
program rewritten a bit more efficiently. It produces the same output as before.

// Prevent a division by zero using the ?.


class NoZeroDiv2 {
public static void main(String args[]) {
for(int i = -5; i < 6; i++)
if(i != 0 ? true : false)
System.out.println("100 / " + i +
" is " + 100 / i);
}
}

Notice the if statement. If i is zero, then the outcome of the if is false, the division by zero is
prevented, and no result is displayed. Otherwise the division takes place.

Riccardo Flask 40 | P a g e
JAVA for Beginners

switch Statement (case of)

The switch provides for a multi-way branch. Thus, it enables a program to select among several
alternatives. Although a series of nested if statements can perform multi-way tests, for many
situations the switch is a more efficient approach.

switch(expression) {

case constant1:

statement sequence

break;

case constant2:

statement sequence

break;

case constant3:

statement sequence

break;

...

default:

statement sequence

The switch expression can be of type char, byte, short, or int. (Floating-point expressions,
for example, are not allowed.)
Frequently, the expression controlling the switch is simply a variable.
The case constants must be literals of a type compatible with the expression.
No two case constants in the same switch can have identical values.
The default statement sequence is executed if no case constant matches the expression.
The default is optional; if it is not present, no action takes place if all matches fail. When a
match is found, the statements associated with that case are executed until the break is
encountered or, in the case of default or the last case, until the end of the switch is reached.

Riccardo Flask 41 | P a g e
JAVA for Beginners

The following program demonstrates the switch.

// Demonstrate the switch.

class SwitchDemo {

public static void main(String args[]) {

int i;

for(i=0; i<10; i++)

switch(i) {

case 0:

System.out.println("i is zero");

break;

case 1:

System.out.println("i is one");

break;

case 2:

System.out.println("i is two");

break;

case 3:

System.out.println("i is three");

break;

case 4:

System.out.println("i is four");

break;

default:

System.out.println("i is five or more");

Riccardo Flask 42 | P a g e
JAVA for Beginners

The output produced by this program is shown here:

i is zero
i is one
i is two
i is three
i is four
i is five or more
i is five or more
i is five or more
i is five or more
i is five or more

The break statement is optional, although most applications of the switch will use it. When
encountered within the statement sequence of a case, the break statement causes program flow to
exit from the entire switch statement and resume at the next statement outside the switch.
However, if a break statement does not end the statement sequence associated with a case, then all
the statements at and following the matching case will be executed until a break (or the end of the
switch) is encountered. For example,

// Demonstrate the switch without break statements.

class NoBreak {

public static void main(String args[]) {

int i;

for(i=0; i<=5; i++) {

switch(i) {

case 0:

System.out.println("i is less than one");

case 1:

System.out.println("i is less than two");

case 2:

System.out.println("i is less than three");

case 3:

System.out.println("i is less than four");

case 4:

System.out.println("i is less than five");

Riccardo Flask 43 | P a g e
JAVA for Beginners

System.out.println();

Output:

i is less than one


i is less than two
i is less than three
i is less than four
i is less than five
i is less than two
i is less than three
i is less than four
i is less than five
i is less than three
i is less than four
i is less than five
i is less than four
i is less than five
i is less than five

Execution will continue into the next case if no break statement is present.

You can have empty cases, as shown in this example:

switch(i) {

case 1:

case 2:

case 3: System.out.println("i is 1, 2 or 3");

break;

case 4: System.out.println("i is 4");

break;

Riccardo Flask 44 | P a g e
JAVA for Beginners

Nested switch
switch(ch1) {

case 'A': System.out.println("This A is part of outer


switch.");

switch(ch2) {

case 'A':

System.out.println("This A is part of inner


switch");

break;

case 'B': // ...

} // end of inner switch

break;

case 'B': // ...

Mini-Project Java Help System (Help.java)


Your program should display the following options on screen:

Help on:

1. if
2. switch

Choose one:

To accomplish this, you will use the statement

System.out.println("Help on:");

System.out.println(" 1. if");

System.out.println(" 2. switch");

System.out.print("Choose one:

Next, the program obtains the user’s selection

choice = (char) System.in.read();

Once the selection has been obtained, the display the syntax for the selected statement.

Riccardo Flask 45 | P a g e
JAVA for Beginners

switch(choice) {

case '1':

System.out.println("The if:\

System.out.println("if(condition)

System.out.println("else statement;");

break;

case '2':

System.out.println("The switch:\

System.out.println("switch(

System.out.println(" case

System.out.println(" statement default clause catches invalid choices. For


example, if the user enters 3, no case constants
System.out.println(" break;");
will match, causing the default sequence to
System.out.println(" // ..."); execute.

System.out.println("}");

break;

default:

System.out.print("Selection not found.");

Complete Listing

/*

Project 3-1

A simple help system.

*/

class Help {

public static void main(String args[])

throws java.io.IOException {

Riccardo Flask 46 | P a g e
JAVA for Beginners

char choice;

System.out.println("Help on:");

System.out.println(" 1. if");

System.out.println(" 2. switch");

System.out.print("Choose one: ");

choice = (char) System.in.read();

System.out.println("\n");

switch(choice) {

case '1':

System.out.println("The if:\n");

System.out.println("if(condition) statement;");

System.out.println("else statement;");

break;

case '2':

System.out.println("The switch:\n");

System.out.println("switch(expression) {");

System.out.println(" case constant:");

System.out.println(" statement sequence");

System.out.println(" break;");

System.out.println(" // ...");

System.out.println("}");

break;

default:

System.out.print("Selection not found.");

Riccardo Flask 47 | P a g e
JAVA for Beginners

Sample run:

Help on:

1. if

2. switch

Choose one: 1

The if:

if(condition) statement;

else statement;

The for Loop

Loops are structures used to make the program repeat one or many instructions for ‘n’ times as
specified in the declaration of the loop.

The for Loop can be used for just one statement:

for(initialization; condition; iteration) statement;

or to repeat a block of code:

for(initialization; condition; iteration)

statement sequence

Initialization = assignment statement that sets the initial value of the loop control variable,
(counter)
Condition = Boolean expression that determines whether or not the loop will repeat
Iteration = amount by which the loop control variable will change each time the loop is
repeated.

The for loop executes only/till the condition is true.

Riccardo Flask 48 | P a g e

You might also like