Programmierpraktikum




Claudius Gros, SS2012

Institut für theoretische Physik
Goethe-University Frankfurt a.M.

Java - Control Flow


controlling the flow



logical operators

SymbolDescriptionExamples
<  <=  >  >= less/-equal, greater/-equal if (i<=8) {}
==   !=equal, unequal if (i==3) {}
&&   ||   !logical AND, OR, NOT if ((a==0)&&(b!=3)) {}
instanceofobject type comparison if (s instanceof String) {}

conditional if

conditional – if … then … else

public class IfThenElse {
  public static void main(String[] args) {

    if (args.length == 1) {
      System.out.println("one: " + args[0]);
    }

    if (args.length == 2) {
      System.out.println("two: " + args[0] + " " + args[1]);
    }

    if (args.length == 1) {
      System.out.println("one");
    } else {
      System.out.println("not one");
    }

    if (args.length > 2) 
      System.out.println("more than two parameters");
  }
}

nested if

conditional – nested if

public class NestedIf {

  public static void main(String[] args) {
    if (args.length == 0)
      System.out.println("zero");
    else if (args.length == 1)
      System.out.println("one");
    else if (args.length == 2)
      System.out.println("two");
    else if (args.length == 3)
      System.out.println("three");
    else
      System.out.println("more");
  }
}

conditional switch

conditional – switch

public class Switch {

  public static void main(String[] args) {
    char operator = args[0].charAt(0); 
       // get first letter of first parameter in command line

    int operand1 = 12;
    int operand2 = 4;
 
    switch (operator) {
    case '+':
      System.out.println(operand1 + operand2);
      break;
    case '-':
      System.out.println(operand1 - operand2);
      break;
    case '*':
      System.out.println(operand1 * operand2);
      break;
    case '/':
      System.out.println(operand1 / operand2);
      break;
    default:
      System.out.println("unknown operator");
      break;
    }
  }
}

control Flow: loop while

loop – while

public class While {
  public static void main(String[] args) {

    int i = 0;
    while(i <= 100){
      System.out.println(i);
      i += 10;
    }
  }
}

do … while - loop

loop – do … while

import java.util.Scanner;

public class DoWhile {
  public static void main(String[] args) {

    int i = 0;
    do {
      System.out.println(i);
      i += 10;
    } while (i <= 100);
 
    Scanner scanner = new Scanner(System.in);
    System.out.println(scanner.delimiter());

    String input;
    do {
      input = scanner.next();
    } while (!input.equalsIgnoreCase("quit"));
  }
}

for - loop

loop – for

public class For {
  public static void main(String[] args) {

    for (int i = 0; i < 10; i++) {
      System.out.println(i);
    }
  }
}

break & continue

loop – break & continue

public class BreakContinue {
  public static void main(String[] args) {

    while(true){   // infinite loop
                   // label α
      int i = (int) Math.round(Math.random() * 100); // random number ∈ [0, 99]
      if(i > 50)
        continue;  // re-entry the loop (go to label α)
      System.out.print(i + ", ");
      if(i == 0)
        break;     // break out of the loop (go to label β)
    }
                   // label β
    System.out.println("done");
  }
}

throwing and catching exceptions

exception – try … catch … finally

example: exception handling

public class TryCatchFinally {
/** This function throws an artimetic runtime exception
  * whenever a division by zero is perfomed.
  */
  public static int devide (int dividend, int divisor)         
         throws ArithmeticException{
    if (divisor == 0)
      {
      throw new ArithmeticException("division by zero");
      } else
    return dividend / divisor;
  }  // end of TryCatchFinally.divide()

/** Entry point.
  */
  public static void main(String[] args) {
    try{
       int result = TryCatchFinally.devide(Integer.parseInt(args[0]), 
                                           Integer.parseInt(args[1]));
       System.out.println(result);
       } catch(ArithmeticException exception)
         {           // thrown by TryCatchFinally.devide()
         System.out.println("Division by zero!");
         } catch(ArrayIndexOutOfBoundsException exception)
           {         // thrown by calling args[]
           System.out.println("Provide two parameters!");
           System.out.println(exception.toString());
           } catch(NumberFormatException exception)
             {       // thrown by Integer.parseInt()
             System.out.println("Provide only integer numbers!");
             } finally
               {     // always executed
               System.out.println("Done with or without error.");
               }
  }  // end of TryCatchFinally.main()
}    // end of class TryCatchFinally()

exercise: number game

The computer chooses a random integer number of a given interval.
The user tries to guess the number while the computer gives the feedbacks "too high" or "too low".

solution: number game

import java.util.Scanner;
public class NumberGame {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in).useDelimiter("\n");
    int min = 0, max = 100, input = 0, numberOfGuesses = 0;
    int random = (int) Math.round(Math.random() * (max - min)) + min;

    System.out.println("Guess the random integer number between " + min + " and " + max + "!");
    do {
      numberOfGuesses++;
      while (true) {
        System.out.print("guess " + numberOfGuesses + ": ");
        try {
          input = Integer.parseInt(scanner.next());
          break;
        } catch (NumberFormatException exception) {
          System.out.println("Integer number requested!");
        }
      }
      if (input < random) {
        System.out.println(input + " is too low.");
      } else if (input > random) {
        System.out.println(input + " is too high.");
      }
    } while (input != random);
    System.out.println(input + " is correct!");
  }
}

exercise: factorial (iterative)

The computer has to calculate the factorial of a non-negative integer number given by the user using iteration.

factorials via iteration

import java.math.BigInteger;         // arbitrary length integers

public class IterativeFactorial {
/** Factorial using BigIntegers.
  */
  public static BigInteger factorial(int arg) {
    BigInteger result = BigInteger.valueOf(1);
    for (int i = 2; i <= arg; i++) {
      result = result.multiply(BigInteger.valueOf(i)); // ℤ
    }
    return result; // only correct if arg ≥ 0
  }

/** Factorial using Long integers.
  */
  public static long factorial(byte arg) {
    long result = 1;
    for (byte i = 2; i <= arg; i++) {
      result *= i; // [−9,223,372,036,854,775,808, 9,223,372,036,854,775,807]
    }
    return result; // only correct if arg ∈ [0, 20]
  }

  public static void main(String[] args) {
    try {

      int intNumber = Integer.parseInt(args[0]); // [−2,147,483,648, 2,147,483,647]
      BigInteger bigIntegerFactorial = IterativeFactorial.factorial(intNumber);

      System.out.println(intNumber + "! = " + bigIntegerFactorial);

      byte byteNumber = Byte.parseByte(args[0]); // [−128, 127] 
      long longFactorial = IterativeFactorial.factorial(byteNumber);

      System.out.println(byteNumber + "! = " + longFactorial);
    } catch (Exception exception) {
      System.out.println("An error occured!");
      System.out.println("usage: java IterativeFactorial ");
    }
  }
}

factorials via recursion

public class Recursion {

  public static void down(int i) {
    System.out.println(i);
    if (i > 0) 
      Recursion.down(i - 1);
  }

  public static int sum(int i){
    if(i > 0){
      return i + sum(i - 1);
    }else{
      return i;
    }
  }

  public static void main(String[] args) {
    Recursion.down(10);
    System.out.println("100*101/2 = " + Recursion.sum(100));
  }
}

recursion: Fibonacci series

training suggestion
write a code for evaluating the n-th Fibonacci number

possible solution

public class Fibonacci {

  public static long fibonacci(int arg) {
    switch (arg) {
    case 0:
      return 0; // f_0 := 0
    case 1:
      return 1; // f_1 := 1
    default:
      return Fibonacci.fibonacci(arg - 1) + Fibonacci.fibonacci(arg - 2); 
                // f_n := f_(n-1) + f_(n-2)
    }
  }

  public static void main(String[] args) {
    try {
      int number = Integer.parseInt(args[0]);
      long fibonacci = Fibonacci.fibonacci(number);
      System.out.println("f_" + number + " = " + fibonacci);
    } catch (Exception exception) {
      System.out.println("An error occured!");
      System.out.println("usage: java Fibonacci ");
    }
  }
}

loops and sums

public class TwoSum {

public static void main(String args[]) {
   double sum, smallNumber;
   double bigNumber = 1.0;
   int n = 100;
// *** 
// *** with not too small number first
// *** 
   for (int exponent=4;exponent<19;exponent=exponent+2)
     {
     System.out.printf("exponent: %d\n",exponent);
     smallNumber = Math.pow(10.0,-exponent);
     sum = n*smallNumber + bigNumber;  // sum of smallNumber first
     System.out.printf("adding sum of small numbers to big number: %20.18f\n",
                       sum);
//
     sum = bigNumber;
     for (int i=0;i<n;i++)
       sum += smallNumber;
     System.out.printf("       adding small numbers to big number: %20.18f\n",
                       sum);
     System.out.println(" ");
//
     } // end of loop over exponents
  }    // end of TwoSum.main()
}      // end of TwoSum

numerics: summation

large number of small numbers

import java.lang.Math;   // standard import, always useful
/** Series summation may depend on the order.
  * Summing 1/k^2 upwards and downwards.
  */
public class SeriesSummation {

public static void main(String[] args) {
  double exact = Math.PI*Math.PI/6.0;  // infinite series
  double resultUp   = 0.0;
  double resultDown = 0.0;
  int maxN = 0;
  for (int ii=4; ii<21; ii+=4)
    {
    maxN = ii*10000000;
    resultUp   = SeriesSummation.summationUp(maxN);  // both calls
    resultDown = summationDown(maxN);                // possible
    System.out.printf("%20.16f %20.16f %20.16f\n",
                      exact,resultUp,resultDown);
    }
  System.out.println(" ");
  System.out.printf("exact result : %20.16f\n",exact);
  System.out.printf("summing down : %20.16f\n",resultDown);
  System.out.printf("  summing up : %20.16f\n",resultUp);
  System.out.printf("       error :            ^^\n");
  System.out.printf("        maxN : %d\n",maxN);
}

/** Summing upwards.
  */
public static double summationUp(int maxN) {
  double result = 0.0;
  for (int i=1; i<=maxN; i++)
    result += 1.0/(1.0*i*i);
  return result;
  }    //  end of summationUP

/** Summing downwards.
  */
public static double summationDown(int maxN) {
  double result = 0.0;
  for (int i=maxN; i>0; i--)
    result += 1.0/(1.0*i*i);
  return result;
  }    //  end of summationUP

}    //  end of class seriesSummation

  1.6449340668482264   1.6449340418154346   1.6449340418482268
  1.6449340668482264   1.6449340545247193   1.6449340543482265
  1.6449340668482264   1.6449340578345750   1.6449340585148930
  1.6449340668482264   1.6449340578345750   1.6449340605982263
  1.6449340668482264   1.6449340578345750   1.6449340618482264
 
exact result :   1.6449340668482264
summing down :   1.6449340618482264
  summing up :   1.6449340578345750
       error :            ^^
        maxN : 200000000