Sitzung: Jeden Freitag in der Vorlesungszeit ab 16 Uhr c. t. im MAR 0.005. In der vorlesungsfreien Zeit unregelmäßig (Jemensch da?). Macht mit!

Javakurs/Übungsaufgaben/OOPStateCharts/Musterloesung: Unterschied zwischen den Versionen

K (Die Seite wurde neu angelegt: „Lösung: (kompilierbar in nur einer Datei ...) <pre> import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Base Cl…“)
 
(kein Unterschied)

Aktuelle Version vom 11. März 2011, 00:07 Uhr

Lösung: (kompilierbar in nur einer Datei ...)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Base Class for all states
 */
class State {
	// ! returns a new state, if transition is correct
	public State transition(String signal) {
		return this;
	}
}

/**
 * First class to be used in this state chart
 */
class InitialState extends State {
	// ! returns a new state, if transition is correct
	@Override
	public State transition(String signal) {
		if (signal.equals("start")) {
			return new StartedState();
		} else {
			System.out.println("!! signal \"" + signal + "\" not found !!");
			return this;
		}
	}
}

/**
 * First class to be used in this state chart
 */
class StartedState extends State {
	// ! returns a new state, if transition is correct
	@Override
	public State transition(String signal) {
		if (signal.equals("end")) {
			return new InitialState();
		} else if (signal.equals("exit")) {
			return null;
		} else {
			System.out.println("!! signal \"" + signal + "\" not found !!");
			return this;
		}
	}
}

/**
 * Class file starting main loop
 */
public class StateCharts {
	/**
	 * Main class, creating the state chart
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// set the state chart to be initial at state initial
		State current_state = new InitialState();

		// loop through the state till exit is reached
		while (current_state != null) {
			// print information about current class
			System.out.println("Current state: "
					+ current_state.getClass().getName());

			// get signal for next state
			System.out.print("signal to be send: ");
			InputStreamReader input = new InputStreamReader(System.in);
			BufferedReader reader = new BufferedReader(input);
			String signal = reader.readLine();

			// get next state if needed
			current_state = current_state.transition(signal);
			System.out.println();
		}

		// inform user
		System.out.println("StateChart is at end state.");
	}
}