Ami A.

asked • 08/16/23

I need to fix climb() and reverse() methods to alter the position and climbingUp variables within the Monkey class itself.

I designed a class called Monkey, which represents a monkey climbing along a vertical vine in the jungle.

The monkey can only climb for one unit of distance at a time. The direction in which it is climbing can be either up or down. The monkey can decide to change direction.


I need to fix climb() and reverse() methods to alter the position and climbingUp variables within the Monkey class itself.


import java.util.Scanner;

public class Monkey

{

//Declare a private integer variable

private int position;


//Declare a primitive database which can be true or false

private boolean climbingUp;


//The monkey starts at position 0, climbing up

public Monkey()

{

position = 0;

climbingUp = true;

}


//Decide the direction

public String toString()

{

String direction = climbingUp ? "Up" : "Down";

return "Position: " + position + ", Climbing: " + direction;

}


//Ask for the next action

public static void main(String[] args)

{

//Create a Scanner object

Monkey monkey = new Monkey();

Scanner scanner = new Scanner(System.in);


//Create character objects

char choice;


//Create a do-while loop

do

{

//Print the results

System.out.println("Choose an action:");

System.out.println("O: Output position and direction");

System.out.println("C: Climb");

System.out.println("R: Reverse direction");

System.out.println("E: Exit");


//

choice = scanner.nextLine().toUpperCase().charAt(0);


//Switch the statement

switch (choice)

{

//Case statements

case 'O':

System.out.println(monkey.toString());

break;


case 'C':

monkey.position += monkey.climbingUp ? 1 : -1;

break;


case 'R':

monkey.climbingUp = !monkey.climbingUp;

break;


case 'E':

System.out.println("Exiting the program.");

break;


//If there is no case match in a swich

default:

System.out.println("Invalid choice. Try again.");

}


//Exite the program when a user type the letter 'E'

} while (choice != 'E');

scanner.close();

}

}


1 Expert Answer

By:

Lauren S. answered • 08/16/23

Tutor
New to Wyzant

Lab Tech/Teaching Assistant | Java, Python, Math

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.