Using else if

Figure 198. Equivalent: if ... else if ... else Slide presentation Create comment in forum
if ('A' == grade || 'B' == grade) {
   result = "Excellent";
} else if ('C' == grade) {
   result = "O.k.";
} else if ('D' == grade) {
   result = "Passed";
} else {
   result = "Failed";
}
Equivalent: if ... else if ... else

Figure 199. if ... else if ... else syntax Slide presentation Create comment in forum
if (booleanExpression)
   (block | statement)
[else if (booleanExpression)
   (block | statement) ]* 
[else
  (block | statement) ] 

The pair of braces [...] indicates an optional clause. The asterisk * indicates an arbitrary number of repetitions (zero to infinity).

The second pair of braces [...] again indicates an optional clause.

Thus only the if (booleanExpression) (block | statement) clause is mandatory.


Figure 200. User input recipe Slide presentation Create comment in forum
import java.util.Scanner;
public class App {
  public static void main(String[] args){

    try (final Scanner scan = 
       new Scanner(System.in)) {

      System.out.print("Enter a value:");

      final int value = scan.nextInt();

      System.out.println(
         "You entered " + value);
    }
  }
}
Enter a value:123
You entered 123

See nextBoolean(), nextByte() and friends.


exercise No. 60

Post modifying an exam's marking Create comment in forum

Q:

After completely marking an examination a lecturer decides to globally add a number extra bonus points to a specific task . The task does have an upper limit of points to be awarded at maximum. We provide an example:

On completely fulfilling a given task 12 points will be awarded. So after marking the exam participants' points range from 0 to 12 points being represented by the variable pointsReached.

After completing his marking our lecturer wants to add three more points to all participants without breaching the 12 point limit.

Complete the following code by assigning this modified number of points to the variable newResult.

public static void main(String[] args) {

  int pointsReached = 1;
  int maximumPoints = 12;
  int pointsToAdd = 3;

  final int newResult;

  // TODO: Assignment to variable newResult

  System.out.println("New Result:" + newResult);
}

A:

The basic task is to add up the values of pointsReached and pointsToAdd. When exceeding the limit we just assign the limit itself:

public static void main(String[] args) {

  final int pointsReached = 1;
  final int maximumPoints = 12;
  final int pointsToAdd = 3;

  final int newResult;

  if (maximumPoints <= pointsReached + pointsToAdd) {
    newResult = maximumPoints;
  } else {
    newResult = pointsReached + pointsToAdd;
  }

  System.out.println("New Result:" + newResult);
}

This basically means calculating the minimum of the two expressions pointsReached + pointsToAdd and maximumPoints. This may as well be be implemented by:

public static void main(String[] args) {

  final int pointsReached = 1;
  final int maximumPoints = 12;
  final int pointsToAdd = 3;

  final int newResult = Math.min(maximumPoints, pointsReached + pointsToAdd);

  System.out.println("New Result:" + newResult);
}

You will fully understand the above expression Math.min(...) after finishing the Static Final Variables section of [Kurniawan].

exercise No. 61

At the bar Create comment in forum

Q:

This example uses existing program code to be explained later. You'll implement an interactive application which implements a dialogue with a user asking for input to be entered in a terminal like window as being shown in the following video:

Figure 201. Using a Scanner class collecting user input.

A bar uses a software system for picking up orders. The bar will serve just orange juice and beer. For legal reasons the latter will only be served to persons of at least 16 years of age. We show three possible user dialogues:

  1. On offer:
      1=Beer
      2=Orange juice
    
    Your choice:>1
    Tell me your age please:>15
    Sorry, we are not allowed to serve beer to underage customers
  2. On offer:
      1=Beer
      2=Orange juice
    
    Your choice:>2
    o.K.
  3. On offer:
      1=Beer
      2=Orange juice
    
    Your choice:>4
    Sorry, invalid choice

Since you may not yet know how to enable Java applications asking for user input simply use the following recipe to get started:

public static void main(String[] args) {

  try (final Scanner scan = new Scanner(System.in)) { // Creating a scanner for reading user input

    System.out.print("Please enter a value:");
    final int userInput = scan.nextInt();

    System.out.println("You entered: " + userInput);
    // TODO: Implement «at the bar» logic

  } // Auto closing scanner
}

Copy this boilerplate code into your IDE. The IDE will assist you adding a required import java.util.Scanner; statement in your code's header section. Execute this code. You should see a dialogue like:

Please enter a value:112
You entered: 112

Then extend the above code implementing the desired behaviour.

A:

package start;

import java.util.Scanner;

public class BarOrder {

    public static void main(String[] args) {

        final Scanner scan = new Scanner(System.in);
        System.out.print("On offer:\n  1=Beer\n  2=Orange juice\n\nYour choice:>" );

        final int beverageChoice = scan.nextInt(); // Read user input

        switch (beverageChoice) {
            case 1:
                System.out.print("Tell me your age please:>");
                final int age = scan.nextInt();
                if (age < 16) {
                    System.out.println("Sorry, we are not allowed to serve beer to underage customers");
                } else {
                    System.out.println("o.K.");
                }
                break;

            case 2:
                System.out.println("o.K.");
                break;

            default:
                System.err.println("Sorry, invalid choice");
                break;
        }
        scan.close();
    }
}

exercise No. 62

Roman numerals Create comment in forum

Q:

Write an application which turns a positive integer values up to and including 10 into Roman numeral representation:

Enter a number:>9
IX

Regarding user input you may start from ??? again. If the user enters a value smaller than one or greater than ten the following output is to be expected:

Enter a number:>11
Decimal value 11 not yet implemented

Tip

You may use a series of if () {...} else if () {...} ... statements.

A:

try (final Scanner scan = new Scanner(System.in)) {

  System.out.print("Enter a number:>");
   final int number = scan.nextInt();

   if (1 == number) {
      System.out.println("I");
   } else if (2 == number) {
      System.out.println("II");
   } else if (3 == number) {
       System.out.println("III");
   } else if (4 == number) {
       System.out.println("IV");
   } else if (5 == number) {
       System.out.println("V");
   } else if (6 == number) {
       System.out.println("VI");
   } else if (7 == number) {
       System.out.println("VII");
   } else if (8 == number) {
       System.out.println("VIII");
   } else if (9 == number) {
       System.out.println("IX");
   } else if (10 == number) {
       System.out.println("X");
   } else {
       System.out.println("Decimal value " + number + " not yet implemented");
   }
}
Figure 202. Converting numbers to day's names Slide presentation Create comment in forum

Task: Convert day's numbers to day's names

1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday

Figure 203. Implementing number to day's names Slide presentation Create comment in forum
try (final Scanner scan = new Scanner(System.in)) {
  System.out.print("Enter a weekday number (1=Monday, 2=Tuesday,...) : ");

  final int number = scan.nextInt();

  if (1 == number) {
      System.out.println("Monday");
  } else if (2 == number) {
      System.out.println("Tuesday");
   ...

  } else if (7 == number) {
      System.out.println("Sunday");
  } else {
      System.out.println("Invalid number " + number);
  }
}