Read this chapter, which reviews how computers make decisions using if statements. As you read this tutorial, you will understand that sometimes it is important to evaluate the value of an expression and perform a task if the value comes out to be true and another task if it is false. In particular, try the simulated program under the heading "Simulated Program" to see how a different response is presented to the user based on if a number is positive or negative.
Pay special attention to the "More Than One Statement per Branch" header to learn how the 'else' statement is used when there is more than one choice.
18. Number Tester Program
Answer:
Yes. There are ways to arrange the tests. You could first split the group into zero and not-zero.
Then split not-zero into positive and negative. But you will always need two tests, whatever they are.
Number Tester Program
Here is a program that implements the flowchart. The part that corresponds to the nested decision of the flow chart is in red. This is called a nested if statement because it is nested in a branch of an outer if
statement.
Indenting: The "false branch" of the first if
is a complete if
statement. Its two branches are indented relative to the if
they belong to.
import java.util.Scanner; public class NumberTester { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int num; System.out.println("Enter an integer:"); num = scan.nextInt(); if ( num < 0 ) { // true-branch System.out.println("The number " + num + " is negative"); } else { // nested if if ( num > 0 ) { System.out.println("The number " + num + " is positive"); } else { System.out.println("The number " + num + " is zero"); } } System.out.println("Good-bye for now"); // always executed } } |
Question 18: