A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming. The main thing to remember about nested ifs in Java is that an else statement always refers to the nearest if statement that is with in 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)
As the comments indicate, the final else is not associated with if(j < 20), because it is not in the same block (even though it is the nearest if without an else). Rather, the final else is associated with if(i == 10). The inner else refers to if(k > 100), because it is the closest if within the same block.
You can use a nested if to add a further improvement to the guessing game. This addition provides the player with feedback about a wrong guess.
// 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");
}
}
}
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
Friday, December 14, 2018
Nested ifs
December 14, 2018
No comments
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment