Decision Making
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: