Question

I am supposed to reduce redundancy in the code and also make unknown inputs, output "unknown"....

I am supposed to reduce redundancy in the code and also make unknown inputs, output "unknown".

Step 1: Your development manager likes your program but is concerned about code duplication. Roger left a note on your desk, asking about using a feature for automatically converting strings to enumerations.

Change your ToCommand method to employ this JAVA library method. (Hint: Look for a valueOf method).

After converting your ToCommand method, run the program and enter an invalid command (one that does not map to a value in the Commands enumeration). What happens?

Step 2: In the previous step, you learned that the built-in JAVA feature, for converting strings to enumerations, throws an exception if there is no matching value. Thus, while employing the valueOf method dramatically reduces the code required to convert strings to enumerations and allows new enumeration values to be added without changing the ToCommand method, it also poses a problem. Your game can’t crash every time the player enters an invalid command or makes a typo!! In this video, Roger shows you how one of the play testers is concerned that the game is crashing when she enters a command.

Figure out a way to handle these exceptions. If the user enters a command that the game does not recognize, have the game display the output “Unknown.”

CURRENT CODE:

public class Main {

    public static void main(String[] args) {
        System.out.print("Welcome to Zork!\n> ");

        Scanner scanner = new Scanner(System.in);
        String inputString = scanner.nextLine();

        if ("QUIT".equalsIgnoreCase(inputString))
        {
            // Output string initiated if the user inputs "quit"
            System.out.println("Thank you for playing!");
        }
        else if ("LOOK".equalsIgnoreCase(inputString))
        {
            // Output string initiated if the user inputs "look"
            System.out.println("A rubber mat saying " +
                    "‘Welcome to Zork!’ lies by the door.");
        }
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.*;
class Room {

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Room(String name) {
setName(name);
}

@Override
public String toString() {
return name;
}

private String name;
private String description;
}

//**Main.java**

enum Commands {
UNKNOWN,
QUIT,
LOOK,
NORTH,
SOUTH,
EAST,
WEST
}


public class Main {

public static void main(String[] args) {
System.out.println("Welcome to Zork!");


InitializeRoomDescriptions();

SpawnPlayer();

Room currentRoom = rooms[locationX][locationY];
Room previousRoom = currentRoom;

Scanner scanner = new Scanner(System.in);

Commands command = Commands.UNKNOWN;

while (command != Commands.QUIT) {
System.out.println(currentRoom);
System.out.print(">");
String inputString = scanner.nextLine();
command = ToCommand(inputString);

switch (command)
{
case QUIT:
System.out.println("Thank you for playing!");
break;

case LOOK:
System.out.println(currentRoom.getDescription());
break;

case NORTH:
case SOUTH:
case EAST:
case WEST:

Move(command);
currentRoom = rooms[locationX][locationY];
if (currentRoom != previousRoom) {
System.out.println(currentRoom.getDescription());
previousRoom = currentRoom;
}
break;

default:
System.out.println("Unknown command.");
break;
}
}
}

private static Commands ToCommand(String commandString) {
try {
return Commands.valueOf(commandString.trim().toUpperCase());
} catch (IllegalArgumentException ex) {
return Commands.UNKNOWN;
}
}

private static void Move(Commands command) {
if (IsDirection(command) == false)
{
throw new IllegalArgumentException();
}

boolean isValidMove = false;
switch (command)
{

case NORTH:
if (locationY < rooms[locationX].length - 1) {
isValidMove = true;
locationY++;
}
break;

case SOUTH:
if (locationY > 0) {
isValidMove = true;
locationY--;
}
break;

case EAST:
if (locationX < rooms.length - 1) {
isValidMove = true;
locationX++;
}
break;

case WEST:
if (locationX > 0) {
isValidMove = true;
locationX--;
}
break;
}

if (isValidMove == false)
{
System.out.println("The way is blocked!");
}
}

private static boolean IsDirection(Commands command) {
return directions.contains(command);
}

private static void SpawnPlayer(){
Random random = new Random();
locationX = random.nextInt(rooms.length);
locationX = random.nextInt(rooms[0].length);
}
private static void InitializeRoomDescriptions() {
rooms[0][0].setDescription("There's a coat hook on the wall.");
rooms[0][1].setDescription("You see a tidy, cozy kitchen");
rooms[0][2].setDescription("You see a table set for dinner.");
rooms[1][0].setDescription("You are in the living room.");
rooms[1][1].setDescription("You see a bed, a dresser, and a mirror.");
rooms[1][2].setDescription("You are in the bathroom. You see a toilet and a vanity.");
rooms[2][0].setDescription("There is chess set on a table with two chairs on either side.");
rooms[2][1].setDescription("You see a washer and dryer");
rooms[2][2].setDescription("A rubber may saying 'Welcome to Zork!' lies by the door.");
}

private static Room[][] rooms = {
{ new Room("Foyer"), new Room("Kitchen"), new Room("Dining Room") },
{ new Room("Living Room"), new Room("Bedroom"), new Room("Bathroom ") },
{ new Room("Game Room"), new Room("Laundry"), new Room("Porch") }
};

private static int locationX = 0;
private static int locationY = 0;

private static final ArrayList directions = new ArrayList(Arrays.asList(
Commands.NORTH,
Commands.SOUTH,
Commands.EAST,
Commands.WEST));
}

Add a comment
Know the answer?
Add Answer to:
I am supposed to reduce redundancy in the code and also make unknown inputs, output "unknown"....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Why can't the 'length' be resolved? import java.util.*; enum Commands { UNKNOWN, QUIT, LOOK, NORTH, SOUTH,...

    Why can't the 'length' be resolved? import java.util.*; enum Commands { UNKNOWN, QUIT, LOOK, NORTH, SOUTH, EAST, WEST } public class Main { public static void main(String[] args) { System.out.println("Welcome to Zork!"); SpawnPlayer(); Scanner scanner = new Scanner(System.in); Commands command = Commands.UNKNOWN; while (command != Commands.QUIT) { System.out.println(rooms[]locationRow[locationColumn]); System.out.print(">"); String inputString = scanner.nextLine(); command = ToCommand(inputString); switch (command) { case QUIT: System.out.println("Thank you for playing!"); break; case LOOK: System.out.println("A rubber mat saying 'Welcome to Zork!' lies by the door."); break;...

  • Assignment 14.3: Valid Email (10 pts) image source Write a program that takes as input an...

    Assignment 14.3: Valid Email (10 pts) image source Write a program that takes as input an email address, and reports to the user whether or not the email address is valid. For the purposes of this assignment, we will consider a valid email address to be one that contains an @ symbol The program must allow the user to input as many email addresses as desired until the user enters "q" to quit. For each email entered, the program should...

  • (Java) Rewrite the following exercise below to read inputs from a file and write the output...

    (Java) Rewrite the following exercise below to read inputs from a file and write the output of your program in a text file. Ask the user to enter the input filename. Use try-catch when reading the file. Ask the user to enter a text file name to write the output in it. You may use the try-with-resources syntax. An example to get an idea but you need to have your own design: try ( // Create input files Scanner input...

  • The goal of this problem is to practice using appropriate branching statements. You will add to...

    The goal of this problem is to practice using appropriate branching statements. You will add to the main method to take in user input and output a message based on the input. This program emulates a detective questioning an eye-witness of a murder. The detective has three suspects each with a potential murder weapon. Based on the eye-witness's user input, the detective will reach a conclusion about the murderer and the murder weapon. If the witness input is "Amos" the...

  • I need to create a code for this prompt: In this project we will build a...

    I need to create a code for this prompt: In this project we will build a generic UserInput class for getting keyboard input from the user. Implementation: The class UserInput is a 'Methods only' class, and all the methods should be declared static. Look at the TestScanner.java program at the bottom of this page that inputs a string, int and double. It shows you how to use Scanner class to get input from the keyboard. Write FOUR simple methods, one...

  • Need code written for a java eclipse program that will follow the skeleton code. Exams and...

    Need code written for a java eclipse program that will follow the skeleton code. Exams and assignments are weighted You will design a Java grade calculator for this assignment. A user should be able to calculate her/his letter grade in COMS/MIS 207 by inputting their scores obtained on worksheets, assignments and exams into the program. A skeleton code named GradeCompute.java containing the main method and stubs for a few other methods, is provided to you. You must not modify/make changes...

  • So i need help with this program, This program is supposed to ask the user to...

    So i need help with this program, This program is supposed to ask the user to input their weight on earth so I would put "140" then it would ask "enter planet name, Min, Max or all" and if the user typed in all it would display all the planets and your weight on them. Right now Im suck on the part where im required to do a switch statement with a linear search. Below this im going to put...

  • ANS (2) 0R hat output is produced by the following code if user enters these values...

    ANS (2) 0R hat output is produced by the following code if user enters these values for a question asked by the progran .User entered 3 Enter a positive integer value! (enter -1 to end) :3 Enter a positive integer value! (enter -1 to end) five Enter a positive integer value! (enter -1 to end) :7 Enter a positive integer value! (enter -1 to end) :-1 User entered five -User entered 7 ...User entered -1 import java.util.Scanner: class Verify input...

  • Hello, I am wondering what the source code for this problem would be. Thank you so...

    Hello, I am wondering what the source code for this problem would be. Thank you so much. You will write a java program using the Eclipse IDE. The program will allow a user to perform one of two options. The user can look up the dates for a given zodiac sign or enter a date and find what sign corresponds to that date. SIGN START DATE END DATE Aries 3/21 4/19 Taurus 4/20 5/20 Gemini 5/21 6/20 Cancer 6/21 7/22...

  • Lesson is about Input validation, throwing exceptions, overriding toString Here is what I am supposed to...

    Lesson is about Input validation, throwing exceptions, overriding toString Here is what I am supposed to do in the JAVA Language: Model your code from the Time Class Case Study in Chapter 8 of Java How to Program, Late Objects (11th Edition) by Dietel (except the displayTime method and the toUniversalString method). Use a default constructor. The set method will validate that the hourly employee’s rate of pay is not less than $15.00/hour and not greater than $30.00 and validate...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT