Package com.martinandersson.lesson08.enums

Source Code of com.martinandersson.lesson08.enums.Player

package com.martinandersson.lesson08.enums;

import java.io.Console;
import java.io.IOException;
import java.io.UncheckedIOException;
import static java.lang.System.out;

/**
* Some kind of player? The player get a {@code Direction} from the user and
* then print it to console.
*
* @author Martin Andersson (webmaster at martinandersson.com)
*/
public class Player {

    public static void main(String[] args) {
        char x = getCharFromUser();

        final DirectionEnum direction;
       
        /*
         * As an exercise, implement a method in DirectionEnum such that this
         * compile:
         *
         * direction = DirectionEnum.ofKey(x);
         */

        switch (x) {
            case 'W':
                direction = DirectionEnum.UP;
                break;
            case 'S':
                direction = DirectionEnum.DOWN;
                break;
            case 'A':
                direction = DirectionEnum.LEFT;
                break;
            case 'D':
                direction = DirectionEnum.RIGHT;
                break;
            default:
                throw new IllegalArgumentException("Unknown direction.");
        }
       
        // Enum.toString(), by default, return Enum.name()
        out.println("You're going in this direction: " + direction);
       
        // Example of how-to go the other way around (Java will add the valueOf() method to our enum):
        DirectionEnum down = DirectionEnum.valueOf("DOWN");
    }

    private static char getCharFromUser() {
        Console c = System.console();
        c.writer().print("Type in what direction you want to move in (WSAD): ");
        c.writer().flush();

        try {
            return (char) System.console().reader().read();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
TOP

Related Classes of com.martinandersson.lesson08.enums.Player

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.