Othello in Java: Part 1: Data structures

You’ve got a big problem. Someone forces encourages you to implement a complete Othello UI+AI in Java, but you don’t have any idea how to do that. If you already know how to implement the basics and you are interested in more advanced strategy concepts, you might be interested in the other parts of this series (yet to come).

In this multi-part series I will not provide any complete solution to any of the standard Othello tasks. Instead, I will provide (hopefully) helpful hints how to get your coding going and explain how your code works.

Read more

Check Scanner number input boundary in Java

In many cases if you want to create an interactive command line interface, you need to check if a number entered by the user is valid and – if it isn’t – you want the user to re-input it.

Here’s a simple static method to check if a number typed by a user is within a given boundary:

/**
 * Lets the user input an integer value until it satisfies the given
 * conditions
 *
 * @param msg The prompt to ask the user for the value.
 * @param lower The lower boundary, inclusive
 * @param upper The upper boundary, inclusive
*/
private static int guardedInput(String msg, int lower, int upper) {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.print(msg);
        int val = -1;
        try {
        val = scanner.nextInt();
        } catch (InputMismatchException ex) {
        System.out.println("Illegal value: Please type a number!");
        }
        if (val < lower) {
        System.out.println("Illegal value: Must be greater than " + (lower - 1));
        } else if (val > upper) {
        System.out.println("Illegal value: Must be smaller than " + (upper + 1));
        } else {
        return val;
        }
    }
}