Enter an integer: 12 The number 12 is positive Good-bye for now
The false branch is executed because the answer to the
question num < 0
was false.
Here is the program again, done as a flowchart. Because the answer to the question is false, the false branch is performed. The "two-way split" of the program is easy to see in a two dimensional chart. It is harder to see this in a program where line follows line one after another.
import java.util.Scanner;
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 )
System.out.println("The number " +
num + " is negative");
else
System.out.println("The number " +
num + " is positive");
System.out.println("Good-bye for now");
}
}
The flow chart shows the overall logic of the program. Most of the details of syntax are left out. It is often helpful to sketch a flowchart when you are designing a program. You can use the flowchart to get the logic correct, then fill in the details when you write the program.
The user runs the program and enters -5
.
What will the program print?