简体   繁体   English

if / else语句写为循环

[英]If/else statements written as loops

I heard that one can turn the if/else statements into loops, they are somewhat equivalent. 我听说可以将if / else语句转换成循环,它们有点等同。 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. 我基本上正在完成一项任务,必须使用在所有if / else语句中编写的某人代码,并将其转换为包含循环的代码。

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. 好的,我已经开始将上面代码的Living Room部分路径转换为while循环。 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: 测试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: 是的,在汇编语言中,循环使用condition语句和goto语句实现:

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

You can use this approach in C, but not in Java because goto is not permitted. 您可以在C中使用此方法,但不能在Java中使用此方法,因为不允许使用goto。

When program gets to L1, it checks the condition. 当程序到达L1时,它会检查条件。 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. 如果条件满足,程序将继续循环体,之后它将跳转(转到)L1,标记程序中的行号。 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: 如果:

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. 请注意,在循环中我不直接将myVal与循环终止符进行比较。 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. 但是,如果您的整个所需代码在一段while(isPlaying) {}内运行while(isPlaying) {} ,则不需要一堆其他循环。 You just add else if(move#.equalsIgnoreCase("quit") {isPlaying = false; } for all the places you check each move#. 你只需添加else if(move#.equalsIgnoreCase("quit") {isPlaying = false; }为你检查每一步的所有地方#。

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. 对于用户输入的每个命令,没有理由拥有新的move#变量。

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. 这有点复杂,特别是如果你是Java或面向对象的新手,所以或者让每个房间都成为一种方法。 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...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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