繁体   English   中英

if / else语句写为循环

[英]If/else statements written as loops

我听说可以将if / else语句转换成循环,它们有点等同。 有人可以给我一个例子,因为我很难理解转换过程。

好的评论我想我没有正确地提出这个问题。 我基本上正在完成一项任务,必须使用在所有if / else语句中编写的某人代码,并将其转换为包含循环的代码。

我不是要问这个问题的答案,但我想问一个如何做到这一点的例子。 我有很多方法可以做到这一点,下面是代码。 它基本上是一个鬼屋迷宫式的“游戏”,只要你在经过房间后触摸和探索物体就会结束,但没有回溯。 使用循环我必须允许回溯,并允许用户探索尽可能多的项目,并且只有在用户决定结束时才结束游戏。

编辑:

好的,我已经开始将上面代码的Living Room部分路径转换为while循环。 请告诉我它是否看起来不错,如果我能以某种方式改进它,或者如果我犯了任何错误,它似乎运行正常。 我唯一的问题是,当我点击决定去使用胸部时,它要求两次然后结束,它应该只询问一次,与烛台一样。 也许我错过了一些关于“休息”的声明? 但我不知道,因为当我在食品室里,然后回去,我还有其他只包含休息; 它做了应该做的事情......但不是胸部和烛台。

但到目前为止我的代码是:

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();
    }
}
}

测试CLass:

public class LoopyTest {

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

是的,在汇编语言中,循环使用condition语句和goto语句实现:

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

您可以在C中使用此方法,但不能在Java中使用此方法,因为不允许使用goto。

当程序到达L1时,它会检查条件。 如果条件满足,程序将继续循环体,之后它将跳转(转到)L1,标记程序中的行号。 在那里,一个循环。 如果不满足条件,它将会中断,程序将在大括号后的下一行继续{

如果你仔细考虑如何设计它,你可以创建一个与if语句功能相同的循环。

如果:

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

功能上等同

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

其功能相当于同时

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

请注意,在循环中我不直接将myVal与循环终止符进行比较。 这是因为您必须更改比较值才能退出循环,并且您可能不想更改实际变量。

但是,如果您的整个所需代码在一段while(isPlaying) {}内运行while(isPlaying) {} ,则不需要一堆其他循环。 你只需添加else if(move#.equalsIgnoreCase("quit") {isPlaying = false; }为你检查每一步的所有地方#。

我还要补充一点,您当前的代码可以从使用类中受益。 对于用户输入的每个命令,没有理由拥有新的move#变量。

由于不同的房间是一种“国家”。 你可以在使用状态模式时解决它。 每个州由一个对象表示。 使用这些对象,每个对象可以根据它的状态决定下一步做什么。 例如:

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);
        }
    }
}

这有点复杂,特别是如果你是Java或面向对象的新手,所以或者让每个房间都成为一种方法。 根据用户的决定,调用适当的方法等。

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