简体   繁体   English

在Java中重复行的顺序

[英]Repeating a sequence of lines in Java

I can't think how to word what I want to do, but hopefully this will explain. 我不知道该如何表达我想做的事情,但是希望这可以解释。

My friend is making a text-based adventure game, and I was working on separating a part of the game out for ease of management. 我的朋友正在制作一款基于文本的冒险游戏,我正在努力将游戏的一部分分离出来以便于管理。

In the game, the stats of the player, the player inventory and many more get sent to another class. 在游戏中,玩家的统计信息,玩家的库存以及更多信息会被发送到另一个类别。

    static Char player;
    static battle bat;

    public static void directchoice(Char p, battle b) {
    player = p;
    bat = b;
    String[] rightLeft = {"Left", "Right"};
    int direct = JOptionPane.showOptionDialog(null, "Left or Right?", "Option", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, rightLeft, rightLeft[0]);
    if(direct == 0){
        Maze.makeChoice(player, bat);
    }
    if(direct == 1){
        Maze.DoorChoice(player, bat);   
    }
}

As can be seen here, at the beginning of the class, "player" and "bat" are a Character and a Battle. 从这里可以看出,在课程开始时,“玩家”和“蝙蝠”是角色和战斗。 These are imported from the previous section of the game. 这些是从游戏的上一部分导入的。

The "Char p, battle b" seen in the subroutine brackets, along with the "player = p; bat = b;" 在子例程括号中看到的“ Char p,battle b”,以及“ player = p; bat = b;”。 inside the sub have to be repeated for every subroutine. 必须为每个子例程重复子内部的操作。

So for example, here is another subroutine within that class: 因此,例如,这是该类中的另一个子例程:

    public static void DoorChoice(Char p, battle b) {   
    player = p;
    bat = b;
    String[] others = {"Go through door", "Don't go through"};
int checkers = JOptionPane.showOptionDialog(null, "Go through door or not?", "Option", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, others, others[0]);

There are a bunch of others, such as player inventory, monster, and more that also need to be repeated. 还有很多其他内容,例如玩家清单,怪物等等,还需要重复。 What I'm trying to do is create a way of repeating those lines of code automatically for each subroutine, as opposed to having to either type them all out or copy and paste. 我想要做的是创建一种自动为每个子例程重复这些代码行的方法,而不是必须全部键入它们或复制并粘贴。

I tried what I could think of, but being still relatively noobish to java, I don't know what to do to repeat those lines. 我尝试了我能想到的,但是相对于Java来说还是比较笨拙的,我不知道该怎么做来重复这些行。

I hope this makes sense, and I'm sorry if it doesn't :( 我希望这是有道理的,很抱歉,如果没有:(

What you are trying to do is called loop . 您尝试做的事情称为loop There is many types of loops . 循环的类型很多

Here is a generic example of a for-loop : 这是for-loop的一般示例:

for (int counter; counter<repeatXTimes;counter++){
//This will repeat for as long as counter<repeatXTimes, and counter will increase once per loop.
}

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

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