Back to all lessons


Lesson 11

Recursion, arrays

Task 0

Create a new method, which returns a validated from range.


public class CalendarApp {
    public static void main(String[] args) {
        int day = safeInput("Type day", 1, 31);
        int month = safeInput("Type month", 1, 12);
        int year = safeInput("Type year", 1900, 2020);
        // rest of program
    }
    public static int safeInput(String prompt, int min, int max) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        int value;
        while (true) {
            System.out.print(prompt + ": ");
            value = scanner.nextInt();
            if (min <= value && value <= max) {
                return value;
            }
            System.out.println("Validation failed. Value must be in range [" + min + ", " + max + "]");
        }
    }
}
            
Task 1

Count calls of a method.


public class StaticalVariables {
    public static int count = 0;

    public static void main(String[] args) {
        methodCall();
        methodCall();
        methodCall();
        System.out.println(count);
    }
    
    public static void methodCall() {
        System.out.println("Working...");
        count++;
    }
}
            
Task 2

Create a method, which display an array given as parameter reversed.

Task 3

Pass null as a value for array to call any method.

Task 4

Create a method that multiplies every element of copied array by a given number.

Task 5

Read about Fibonacci sequence. Display n-th number of the sequence without using any loop. Tip: call a method in the same method.

Task 6

Display an array without using any loop, nor ready to use methods of Java Api.

Task 7

Using task 5. code, calculate 1000th Fibonacci number. Then create an implementation with any loop and compare it with recursion.