简体   繁体   中英

If/else statements written as loops

I heard that one can turn the if/else statements into loops, they are somewhat equivalent. Could someone give me an example, because I am having a hard time understanding the conversion process.

Ok from the comments I guess I didn't ask the question correctly. I am basically working on an assignment and have to use someone's code which was written in all if/else statements and convert it into a code that includes loops.

I am not asking for the answer to this problem but I am asking for an example on how one would do this. I've pretty much though of a way of doing it, with the code below. It's basically a Haunted House maze type of "game" that ends whenever you touch and explore an object after going through rooms, but there is no backtracking. With loops I have to allow backtracking, and allow the user to explore as many items as possible, and only end the game when the user decides to end it.

EDIT:

Okay, I've started to convert the Living Room section path of the code above into a while loop. Please tell me if it looks good, if I could improve it somehow, or if I made any mistakes, it seems to run fine. The only problem I have is that when I click decide to go use the chest, it asks twice and then ends, it should only ask once, the same with the Candelabra. Maybe I am missing something about the "break" statement? But I don't know because when I am in the pantry, and then go back, and I have the if else contain just break; it does what it is supposed to do... but not with the chest and the candelabra.

But here is my code so far:

public class LoopyHauntedHouse {

private String name; //Player name.
private String location0; //First location selected from door.
private String toFrontDoor = "";
private String atFrontDoor;

//Method asking for user's name, and welcoming the user as well as asking where they'd like to go for the first time.
public void intro()throws MalformedURLException
{
    //URL to image initialized from the original code as needed.
    URL frontDoor = new URL("http://i.imgur.com/2m3giQk.png");

    //Scanner for user input.
    Scanner scnr = new Scanner(System.in);

    //Asking for user's name and welcoming the user.
    name = JOptionPane.showInputDialog(null, "What is your name?");
    JOptionPane.showMessageDialog(null, "Welcome " + name + " to the Haunted House!");

    //Shows starting location.
    JOptionPane.showMessageDialog(null, name + " you're at the front door of the haunted house.", "Title",
    JOptionPane.PLAIN_MESSAGE, new ImageIcon(frontDoor));

    //Asks for first choice of room to start at.
    location0 = JOptionPane.showInputDialog(null, name + " where to next? 'Living Room', 'Dining Room' or 'Stairs'?");
}

//Method for the rest of the program allowing users to walk through the house, backtrack, and interact with objects.
public void startWalking()throws MalformedURLException
{   
    //URLs to images are initialized from the original code as needed.
    URL stairs = new URL("http://i.imgur.com/WuddJUc.png");
    URL bedroom1 = new URL("http://i.imgur.com/HZ6OSyZ.png");
    URL bedroom2 = new URL("http://i.imgur.com/JZORNpd.png");
    URL bathroom = new URL("http://i.imgur.com/onSEc1J.png");
    URL masterBedroom = new URL("http://i.imgur.com/bf4L0sH.png");
    URL masterBathroom = new URL("http://i.imgur.com/yp87dTX.png");
    URL livingRoom = new URL("http://i.imgur.com/7XQD5Pt.png");
    URL bathRoom = new URL("http://i.imgur.com/G0CxjSy.png");
    URL diningRoom = new URL("http://i.imgur.com/gyU9mep.png");
    URL kitchen = new URL("http://i.imgur.com/tTMRCID.png");
    URL pantry = new URL("http://i.imgur.com/zBxPJCs.png");

    while(location0.equalsIgnoreCase("Living Room")||(toFrontDoor.equalsIgnoreCase("Living Room")))
    {
        JOptionPane.showMessageDialog(null, name + " you are now in the Living Room");
        String move1 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Chest' walk to the 'Bathroom' or 'Go back' and go to another room?");

            if(move1.equalsIgnoreCase("Chest"))
            {
                JOptionPane.showMessageDialog(null, name + " a ghost escapes and scares you to death!");
                JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.", 
                JOptionPane.WARNING_MESSAGE, new ImageIcon(livingRoom));
                break;
            }

            else if(move1.equalsIgnoreCase("Bathroom"))
            {
                while(move1.equalsIgnoreCase("Bathroom"))
                {
                JOptionPane.showMessageDialog(null, name + " you are now in the bathroom.");
                String move2 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Mirror', 'Shower', or 'Go back'?");
                    if(move2.equalsIgnoreCase("Shower"))
                    {
                        JOptionPane.showMessageDialog(null, name + " the room suddenly steams up and you feel fingers touching the back of your neck...");
                    }
                    else if(move2.equalsIgnoreCase("Mirror"))
                    {
                        JOptionPane.showMessageDialog(null, name + "you see a bloody face looking back at you!");
                    }
                    else if(move2.equalsIgnoreCase("Go back"))
                    {
                        JOptionPane.showMessageDialog(null, name + " you are now in the Living Room");
                        break;
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, "Please enter a valid option.");
                    }
                }
            }
            else if(move1.equalsIgnoreCase("Go back"))
            {
                toFrontDoor = move1;
                break;
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Please enter a valid option.");
            }
    }

    while(location0.equalsIgnoreCase("Dining Room"))
    {
        JOptionPane.showMessageDialog(null, name + " you are now in the Dining Room");
        String move1 = JOptionPane.showInputDialog(null, name + " would you like to explore the 'Candelabra' or walk to the 'Kitchen'");

        if(move1.equalsIgnoreCase("Candelabra"))
            {
                JOptionPane.showMessageDialog(null, "The candelabra light up by themselves and " + name + " sees a death shadow!");
                JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.", 
                JOptionPane.WARNING_MESSAGE, new ImageIcon(diningRoom));
                break;
            }

        else if(move1.equalsIgnoreCase("Kitchen"))
        {
            while(move1.equalsIgnoreCase("Kitchen"))
            {
                JOptionPane.showMessageDialog(null, name + " you are now in the 'Kitchen'.");
                String move2 = JOptionPane.showInputDialog(null, name + " would you like to explore either the 'Refrigerator' or 'Cabinet' walk to the 'Pantry', or 'Go back'");
                    if(move2.equalsIgnoreCase("Refrigerator"))
                    {
                        JOptionPane.showMessageDialog(null, name + " opens the refrigerator and finds some delicious soul food.");
                    }
                    else if(move2.equalsIgnoreCase("Cabiner"))
                    {
                        JOptionPane.showMessageDialog(null, "The dished and glasses start flying at you as soon as you open the door. " + name + " gets hit in the head and feels themselves moving towards a light.");
                        JOptionPane.showMessageDialog(null, "Game Over! You've died.", "Try Again.", 
                        JOptionPane.WARNING_MESSAGE, new ImageIcon(kitchen));
                        break;
                    }
                    else if(move2.equalsIgnoreCase("Pantry"))
                    {
                        while(move2.equalsIgnoreCase("Pantry"))
                        {
                            JOptionPane.showMessageDialog(null, name + " you are now in the Pantry.");
                            String move3 = JOptionPane.showInputDialog(null, name + " would like to explore the 'Dusty Recipe Box', the 'Broom', or 'Go back'?");
                                if(move3.equalsIgnoreCase("Dusty Recipe Box"))
                                {
                                    JOptionPane.showMessageDialog(null, name + "opens it up and a recipe for chocolate devils food cake appears out of no where.");
                                }
                                else if(move3.equalsIgnoreCase("Broom"))
                                {
                                    JOptionPane.showMessageDialog(null, "As soon as " + name + " touches the broom, it flies up in the air!");
                                }
                                else if(move3.equalsIgnoreCase("Go back"))
                                {
                                    break;
                                }
                                else
                                {
                                    JOptionPane.showMessageDialog(null, "Please enter a valid option.");
                                }
                        }
                    }
                    else if(move2.equalsIgnoreCase("Go back"))
                    {
                        toFrontDoor = move2;
                        break;
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, "Please enter a valid option.");
                    }
            }
        }
    }
}

public void toFrontDoor() throws MalformedURLException
{
    if(toFrontDoor.equalsIgnoreCase("Go back"))
    {
        atFrontDoor = JOptionPane.showInputDialog(null, name + " where to next? 'Living Room', 'Dining Room', 'Stairs', or 'Leave the house'?");
            if(atFrontDoor.equalsIgnoreCase("Leave the house"))
            {
                JOptionPane.showMessageDialog(null, "Game Over! Thanks for playing.");
            }
    }
    else
    {
        startWalking();
    }
}
}

Test CLass:

public class LoopyTest {

    public static void main(String[] args) throws MalformedURLException {
    LoopyHauntedHouse player = new LoopyHauntedHouse();
    player.intro();
    player.startWalking();
    player.toFrontDoor();
}
}

Yes, in assembly language, loops are implemented with condition statement and a goto statement:

L1:  if ( <cond> )
  {
     <loop-body>   
     goto L1 ;
  }

You can use this approach in C, but not in Java because goto is not permitted.

When program gets to L1, it checks the condition. If the condition is met, program will proceed with loop-body, after that it will jump (goto) to L1 which labels a line number in your program. There, a loop. It will break if the condition is not met and program will continue at next line after curly brace { .

You can make a loop that does the functional equivalent of an if statement if you're careful about how you design it.

If:

if(myVal == 1) {
  //do something
}

Functionally equivalent for :

for(int i = myVal; i == 1; ++i) {
  //Do something
}

Functionally equivalent while :

int i = myVal;
while(i == 1) {
 //Do something
 ++i;
}

Notice, that in the loops I don't directly compare myVal against the loop terminator. This is because you have to change the comparison value in order to get out of the loop, and you may not want to change your actually variable.

However, if your entire desired code was running inside a while(isPlaying) {} , you don't need a bunch of other loops. You just add else if(move#.equalsIgnoreCase("quit") {isPlaying = false; } for all the places you check each move#.

I would also add, that your current code could benefit from using classes. There's really no reason to have a new move# variable for each command the user enters.

Since the different rooms are kind of the "state". you could probably solve it when using the state pattern . Each state is represented by one obect. Using those objects, each can decide what to do next based on it's state. For example:

class Room {
    private String roomName;
    private URL icon;
    private List<String> nextRooms;

    public Room(String _roomName, URL _icon, String... _nextRooms) {
        roomName = _roomName;
        icon = _icon;
        nextRooms = new ArrayList<>();
        for (String string : _nextRooms) {
            nextRooms.add(string.toLowerCase());
        }
    }

    public void showInfo(String player) {
        JOptionPane.showMessageDialog(null, player + " you're in " + roomName, "Title",
                JOptionPane.PLAIN_MESSAGE, new ImageIcon(icon));
    }

    public String nextRoomName(String player) {
        StringBuilder sb = new StringBuilder();
        for (String string : nextRooms) {
            sb.append(string).append(", ");
        }
        String roomOptions = sb.toString();

        while(true) {
            String input = JOptionPane.showInputDialog(null, player + " where to next? Your options are: " + roomOptions);
            if(nextRooms.contains(input)) {
                return input;
            }
        }
    }
}

public void start() throws MalformedURLException {
    Map<String, Room> rooms = new HashMap<>();
    rooms.put("room a", new Room("Room A", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room B", "Room C"));
    rooms.put("room b", new Room("Room B", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room A"));
    rooms.put("room c", new Room("Room C", new URL("http://i.imgur.com/7XQD5Pt.png"), "Room A", "Win"));

    String player = JOptionPane.showInputDialog(null, "What is your name?");
    JOptionPane.showMessageDialog(null, "Welcome " + player + " to the Haunted House!");

    Room room = rooms.get("room a");
    while (true) {
        room.showInfo(player);
        String nextRoom = room.nextRoomName(player).toLowerCase();
        if ("win".equalsIgnoreCase(nextRoom)) {
            return;
        }

        if (rooms.containsKey(nextRoom)) {
            room = rooms.get(nextRoom);
        }
    }
}

That's kind of complicated, especially if you're new to Java or Object Oriented , so alternatively make each room a method. And depending on what the user decides, call the appropriate method and so on.

void start() {
    roomA();
}

void roomA() {
    String input = JOptionPane....
    if (input.equals("Room B")) {
        roomB();
    }
}

void roomB() {
    String input = JOptionPane....
    if (input.equals("Room A")) {
        roomA();
    } else if (input.equals("win")) {
        win();
    }
}

void win() {
    JOptionPane.showMessageDialog...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM