User:Kelti/sandbox/Java

A temporary page for a Java course. Send your questions to: juergen@purtz.de


Java I edit

Program Structure; Generate Output edit

1. Create a class First which prints the text: Hello Semey. This is my very first Java program.

public class First {
  public static void main(String[] args) {
    System.out.println("Hello Semey. This is my very first Java program.");
  }
}

2. Create the output:

+----+
|    |
|    |
+----+

3. Create the output:

1
2
3
...
8
9

Conditions edit

Use this program as the basis for the following exercises.

public class BooleanLogic_1 {

  // A template program for boolean logic tests
  public static void main(String[] args) {

    int x = 3;
    int y = 5;

    System.out.println("Start.");
    if (x == 3) {
      System.out.println("Bingo.");
    } else {
      System.out.println("No hit.");
    }
    System.out.println("End.");
  }
}

1. Change the value of x.
2. Change the condition to check x: equal (==), greater (>), smaller-or-equal (<=), not-equal (!=)
3. Test the value of x and y with the operator and (&&): (x == 3 && y == 5)
4. Test the value of x and y with the operator or (||)
5. Test the value of x and y with the operator not (!=)
6. Create an exercise which combines 3, 4, and 5.

More examples:

public class BooleanLogic_2 {

  public static void main(String[] args) {

    int x = 3;
    System.out.println("Start.");

    if (x != 4) {
      System.out.println("The value of x is not 4.");
    }

    if (!(x == 4)) {
      System.out.println("The value of x is not 4.");
    }

    if (x == 3 && false) {
      System.out.println("This is always false - never true.");
    }

    if (x == 12345 || true) {
      System.out.println("This is always true - never false.");
    }

    System.out.println("End.");
  }
}

Loops edit

1. Create the output:

1
2
3
...
98
99

2. Create the output:

1, 3, 5, 7, ... , 97, 99

3. Create the output:

10, 9, 8, ... , 3, 2, 1

4. Create the output:

15, 10, 5, 0, -5, -10, -15

5. Compute the sum from 1 to 5 (= 15).
6. Compute the sum from 1 to 100 (= 5050).


Where is the error? edit

public class Temp {
  for (int i = 0; i < 5; i = i + 1) {
     System.out.println(i);
  }
}
Click to see solution
The class misses the entry point:
   public static void main(String[] args) {

This entry point is (nearly) always necessary!

public class Temp {
public static void main(String[] args) {
  for (int i = 0; i < 5; i = i + 1) {
     System.out.println(i);
  }
}
Click to see solution
The class misses one closing 'curly bracket': }
public class Temp {
  public static void main(String[] args) {
    for (int i = 0; i < 5; i = i + 1) {
       System.out.println(6)
    }
  }
}
Click to see solution
a) The class misses the semicolon at line 4: ; 
b) The 6 is possibly not intend - but syntactically correct.
public class Temp {
  public static void main(String[] args) {
    for (int i = 0; i = 5; i = i + 1) {
       System.out.println(i);
    }
  }
}
Click to see solution
The condition in the for loop is wrong because there is = (assignment operator) instead of == (comparision).

Nested Loops edit

The following exercises use two for-loops, which are nested in each other: a loop within another loop.

1. Create the output (both loops run from 1 to 3):

1 / 1
1 / 2
1 / 3
2 / 1
2 / 2
2 / 3
3 / 1
3 / 2
3 / 3

2. Create the output:

0 1 2 3 4 5 6 7 8 9
10 11 12 ... 17 18 19
20 21 22 ... 27 28 29
...              ...
...              ...
90 91 92 ... 97 98 99

3. Create the output (3 nested loops, one per column):

0  0  0
0  0  1
0  1  0
0  1  1
1  0  0
1  0  1
1  1  0
1  1  1

4. Create the output:

x
xx
xxx
xxxx
xxxxx

5. Create the output:

x
  x
    x
      x
    x
  x
x

6. Create the output (three for-loops):

x
  x
    x
      x
    x
  x
x
x
  x
    x
      x
    x
  x
x
x
  x
    x
      x
    x
  x
x

It's Quiz Time I edit

Which value has the variable k at the end of the code snippet?

    int i = 1;
    int j = 1;
    int k = 1;

    for (i = 0; i < 2; i = i + 1) {
      for (j = 0; j < 3; j = j + 1) {
        k = k + 1;
      }
    }
    System.out.println(k);
Click to see solution
The correct answer is: 7. The outer loop (i) runs two times. In each of its runs, the inner loop (j) runs 3 times. Hence 6 cycles in total. But k does not start with 0, it starts with 1!


Which value has the variable k at the end of the code snippet?

    int i = 0;
    int k = 0;

    for (i = 6; i >= 0; i = i - 2) {
      k = k + 1;
    }
    System.out.println(k);
Click to see solution
The correct answer is: 4. The loop decrements the variable i by 2: 6, 4, 2, 0. Consider the greater_or_equal condition.

Which value has the variable k at the end of the code snippet?

    int i = 0;
    int k = 0;

    for (i = 0; i < 10; i = i + 1) {
      if (i > 5 || i >= 7) {
        k = k + 1;
      }
    }
    System.out.println(k);
Click to see solution
The correct answer is: 4. i >= 7 has no effect because of the OR-operator.



Loops plus Conditions edit

1. Create a chessboard: It's a 8 x 8 square with black and white positions like this:

  xx  xx  xx  xx
xx  xx  xx  xx
  xx  xx  xx  xx
xx  xx  xx  xx
  xx  xx  xx  xx
xx  xx  xx  xx
  xx  xx  xx  xx
xx  xx  xx  xx

2. Modify the board to a 12 x 12 square. In an optimal situation this program differs only in 1 position from the previous program: the value for the size changes from 8 to 12 - all other statements keep unchanged.

3. Create a triangle like this. There are many different possiblities: two loops from 1 to 9 each, one loop from 11 to 99 plus some conditions, ... .

11
21 22
31 32 33
...
91 92 93 94 95 96 97 98 99

4. Create diagonal-lines like this (A):

o          
 o         
  o        
   o       
    o      
     o     

or this (B)

     o     
    o         
   o        
  o       
 o      
o     

or this (C)

o     o     
 o   o         
  o o         
   o        
  o o      
 o   o   
o     o

or this (D)

       o  o
      o  o 
     o  o  
    o  o   
   o  o    
  o  o     
 o  o      
o  o       
  o        
 o         
o

5. What will the following code snippet print out?


    int row = 0;
    int column = 0;

    for (row = 0; row < 11; row = row + 1) {
      for (column = 0; column < 11; column = column + 1) {
        // if (row == column) {
        if (row + column == 10) {
          // print a small circle (without newline)
          System.out.print("o");
        } else {
          // print a blank (without newline)
          System.out.print(" ");
        }
      }
      // print a newline at the end of every column
      System.out.println("");
    }

It's Quiz Time II edit

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


    // ---------------------------------------------
    //             Guess the result
    // ---------------------------------------------     

    System.out.println("Start");

    // ---------------------------------------------
    //    int result = 5;
    //
    //    for (int y = 0; y < 3; y = y + 1) {
    //      result = result + 2;
    //      System.out.println("Intermediate result: " + result);
    //    }
    //    System.out.println("The result is: " + result);

    // ----------------------------------------------
    //    int result = 1;
    //
    //    for (int y = 0; y < 5; y = y + 4) {
    //      result = result + 2;
    //      System.out.println("Intermediate result: " + result);
    //    }
    //    System.out.println("The result is: " + result);

    // ---------------------------------------------------
    //    int result = 16;
    //
    //    for (int y = 10; y >= 7; y = y - 1) {
    //      result = result - 2;
    //    }
    //    System.out.println("The result is: " + result);

    // ------------------------------------------------
    //    int result = 0;   
    //
    //    for (int y = 0; y <= 3; y = y + 1) {
    //      result = result + y;
    //      System.out.println("result: " + result + " y: " + y);
    //    }
    //    System.out.println("The result is: " + result);

    // ---------------------------------------------------
    //    String message = "Message: ";   
    //
    //    for (int y = 0; y < 5; y = y + 1) {
    //      message = message + y + " / ";
    //    }
    //    System.out.println(message);

    // ---------------------------------------------------
    //    int result = 0;  
    //
    //    for (int x = 0; x < 5; x = x + 1) {
    //      for (int y = 4; y >= 0; y = y - 1) {
    //        if (x == y) {
    //          result = result + 1;
    //        }
    //      }
    //    }
    //    System.out.println("The result is: " + result);

    // ----------------------------------------------------
    //    int result = 0;   
    //
    //    for (int y = 0; y < 6; y = y + 1) {
    //      if (y == 0 || y == 2 || y == 4) {
    //        result = result + y;
    //      } else {
    //        result = result - y;
    //      }
    //    }
    //    System.out.println("The result is: " + result);

    // -----------------------------------------------------
    System.out.println("End");

  } 
}

Arrays edit

Create a class with 5 variables to hold some student names. For each of the students print the output:

Hello <student name>.
How are you today?
What have you done during the weekend?
<student name>, I wish you much success.


Class: Average and Minimum

  1. Create an array which holds 5 int values. Fill the array with some values, e.g. the age of students.
  2. Show the elements of the array - one line per element.
  3. Compute the average age of the students.
  4. Show the age of the jungest student.


Class: RandomNumbers1

  1. Create an array to store values of data type double.
  2. Create random numbers with the command Math.random() and store them in the array.
  3. Show all created random numbers - they will be in the range from 0 to 1.
  4. Show only those random numbers, which are between 0.5 and 0.6.


Class: RandomNumbers2

  1. Create an array to store values of data type double.
  2. Create random numbers with the command Math.random() and store them in the array.
  3. Show all created random numbers - they will be in the range from 0 to 1.
  4. Compute the average of the random numbers. Which value do you expect (statistics: expected value)?
  5. Run the program several times.
  6. Use a greater array (more random numbers, e.g.: 5, 50, 500, 5.000, 5 million). The average shall be closer to the expected value.

Java II edit