I will survive

Report a typo

Imagine you are creating a survival game. The main character roams an uninhabited island in search of food. The character may be in either of the two states, hungry or satiated, and will react to different actions according to his or her current state.

The template provides a part of the State pattern implementation that already defines the transitions between the states. Your task is to complete the code of the Hungry and Full classes. The following methods must do the following:

  • onFindFood must print Found some great food if the character is hungry or Found some food if the character is satiated.
  • onEat must print Delicious if the character is hungry or Won't eat it right now is the character is satiated.
  • reportState must print I'm hungry if the character is hungry or I'm full if the character is satiated.

See the examples.

Sample Input 1:

eat
skip
get
eat

Sample Output 1:

Won't eat it right now
I'm full
I'm hungry
Found some great food
Delicious
I'm full

Sample Input 2:

skip
get
eat
get
skip

Sample Output 2:

I'm hungry
Found some great food
Delicious
I'm full
Found some food
I'm hungry
Write a program in Java 17
import java.util.List;
import java.util.Scanner;

interface State {
void onFindFood();

void onEat();

void reportState();
}

class Survivor {
private final List<State> states = List.of(new Hungry(), new Satiated());
private int satiation = states.size() - 1;
private State currentState = states.get(satiation);

public void skipTime() {
satiation = Math.max(0, --satiation);
currentState = states.get(satiation);
currentState.reportState();
}

public void getFood() {
currentState.onFindFood();
}

public void eat() {
currentState.onEat();
satiation = Math.min(states.size() - 1, ++satiation);
currentState = states.get(satiation);
currentState.reportState();
}
}

class Hungry implements State {

___

Create a free account to access the full topic