Update #8 Worst code ever :-)

I am finishing the chapter on packages, scope and access. Not the most sexy topic, but I am happy to do it. It was itching already for some time when to use public, private, static, final etc… It was used before (of course), but not really explained. Now it is. Again, not something you will need to know in detail in daily practice, but I sorta think this is fundamental knowledge that is good to have.

As part of this chapter, there was a fun challenge to illustrate scope. The assignment: a program that prints primary school “times” list for a value. E.g. for value 3 : 1 * 3 = 3, 2 * 3 = 6, 3 *3 = 9 etc….

One specific condition: all variables, members, methods and classes have to be called x (or X for the class)!! It results in completely unreadable code, but due to scoping in Java, it can be done. See if you can follow the code 🙂

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        X x = new X(x());
        x.x();
    }

    private static int x(){
        Scanner x = new Scanner(System.in);
        System.out.print("Enter number: ");
        return x.nextInt();
    }
}

and class X:

public class X {

    private int x;

    public X(int x) {
        this.x = x;
    }

    public void x() {
        for (int x = 1; x <=12; x++) {
            System.out.println(x + " times " + this.x + " = " + x * this.x);
        }
    }
}