Number Tester Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Yes. There are other tests that divide the integers into these three groups. 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.

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 )
    {
      // true-branch
      System.out.println("The number " + num + " is negative");

    } 
    else
    { 
      if ( num > 0 )
      { 
        // nested true-branch
        System.out.println("The number " + num + " is positive"); 
      } 
      else
      {
        // nested false-branch
        System.out.println("The number " + num + " is zero");
      }

    }

    System.out.println("Good-bye for now");    // always executed
  }
}

 

QUESTION 18:

Could an if statement be nested inside the true branch of another if statement?