遍历变量Java

时间:2018-07-10 11:59:44

标签: java

我以随机的方式增加每个变量,直到要分配的点的总和等于0。有什么聪明的方法,可以减少方法generate()中的代码量,例如通过迭代变量而不是一一列出?

public class RandomStatsGenerator {

    int Strength = 3;
    int Dexterity = 3;
    int Constitution = 3;
    int Intelligence = 3;
    int Wisdom = 3;
    int Charisma = 3;
    int sum = 45;
    static final int MAX_VALUE = 18;

    public void generate() {
        while (sum> 0 && Strength <= MAX_VALUE) {
            boolean test = getRandomBoolean();
            if (test == true) {
                Strength++;
                sum--;
            }
            test = getRandomBoolean();
            if (test == true && Dexterity <= MAX_VALUE) {
                Dexterity++;
                sum--;
            }
            test = getRandomBoolean();
            if (test == true && Constitution <= MAX_VALUE) {
                Constitution++;
                sum--;
            }
            test = getRandomBoolean();
            if (test == true && Intelligence <= MAX_VALUE) {
                Intelligence++;
                sum--;
            }
            test = getRandomBoolean();
            if (test == true && Wisdom <= MAX_VALUE) {
                Wisdom++;
                sum--;
            }
            test = getRandomBoolean();
            if (test == true && Charisma <= MAX_VALUE) {
                Charisma++;
                sum--;
            }
        }
        System.out.println("Strength: " + Strength + ".");
        System.out.println("Dexterity: " + Dexterity + ".");
        System.out.println("Constitution: " + Constitution + ".");
        System.out.println("Intelligence: " + Intelligence + ".");
        System.out.println("Wisdom: " + Wisdom + ".");
        System.out.println("Charisma: " + Charisma + ".");
    }

    private boolean getRandomBoolean() {
        Random random = new Random();
        return random.nextBoolean();
    }
}

4 个答案:

答案 0 :(得分:2)

通过将相似代码提取为参数化方法,可以减少像

这样的代码重复。

要做到这一点,我们需要稍微转换一下代码,以将相似代码转换为相同代码

public void generate() {
    while (sum> 0 && Strength <= MAX_VALUE) {
        int property = Strength;
        boolean test = getRandomBoolean();            
        if (test == true && property <= MAX_VALUE) { // added second condition to catch up with the following ifs
            property++;
            sum--;
        }
        Strength = property;

        property = Dexterity;
        test = getRandomBoolean();
        if (test == true && property <= MAX_VALUE) {
            property++;
            sum--;
        }
        Dexterity = property;
        // same for the rest

现在您有5行重复的代码:

        test = getRandomBoolean();
        if (test == true && property <= MAX_VALUE) {
            property++;
            sum--;
        }

您可以选择这5行的第一个匹配项,然后应用IDE的 extract方法重构。您的IDE将替换所有出现的所选行。

public void generate() {
    while (sum> 0 && Strength <= MAX_VALUE) {
        int property = Strength;
        property=extracted(property);
        Strength = property;

        property = Dexterity;
        property=extracted(property);
        Dexterity = property;
        // same for the rest
}
private int extracted(int property){
        test = getRandomBoolean();
        if (test == true && property <= MAX_VALUE) {
            property++;
            sum--;
        }
        return property;
}

当然,您应该在提取时给新方法一个更好的名称。我只是保留了IDE所建议的名称。

最后,您可以在原始方法中内联变量:

  public void generate() {
        while (sum> 0 && Strength <= MAX_VALUE) {
            Strength = extracted(Strength);
            Dexterity = extracted(Dexterity);
            // same for the rest
    }

答案 1 :(得分:1)

为您的属性创建一个枚举,

public enum Attribute {
  STRENGTH,
  DEXTERITY,
  CONSTITUTION,
  INTELLIGENCE,
  WISDOM,
  CHARISMA;
}

然后,创建属性与其值的映射:

Map<Attribute, Integer> attributeValues = new HashMap<>();
attributeValues.put(Attribute.STRENGTH, 3);
attributeValues.put(Attribute.DEXTERITY, 3);
// ...
attributeValues.put(Attribute.CHARISMA, 3);

从地图上选择一个随机属性,并将其增加:

Random rand = new Random();
Attribute toIncrement = Attribute.values()[rand.nextInt(Attributes.values().length)];
attributeValues.compute(toIncrement, (k, v) -> v + 1);

将其放入一个循环中,添加用于跟踪总和的代码,然后就应该完成了。

顺便说一句,我不会遍历每次迭代的所有属性,如果要增加随机布尔值,请检查每个属性,因为这将有利于增加的第一个属性。

答案 2 :(得分:0)

您可以使用映射并在while循环中迭代一组条目:

private Map<String, Integer> map = new HashMap<>();
{
    map.put("Strength", 3);
    map.put("Dexterity", 3);
    map.put("Constitution", 3);
    map.put("Intelligence", 3);
    map.put("Wisdom", 3);
    map.put("Charisma", 3);
}

int sum = 45;

public void generate() {
    while (sum > 0 && map.get("Strength") <= MAX_VALUE) {

        map.entrySet().forEach(entry -> {
            boolean test = getRandomBoolean();
            if (test) {
                map.merge(entry.getKey(), 1, (a, b) -> a + b);
                sum--;
            }
        });
    }

    map.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " 
       + entry.getValue() + "."));
}

如果所有变量的默认值为3,您甚至可以使用列表进一步简化它:

List<String> keys = Arrays.asList("Stength", "Dexterity", 
        "Constitution", "Intelligence", "Wisdom", "Charisma");
private Map<String, Integer> map = new HashMap<>();

int sum = 45;

public void generate() {
    do {
        map.entrySet().forEach(entry -> {
            boolean test = getRandomBoolean();
            if (test) {
                map.merge(entry.getKey(), 3, (a, b) -> a + b);
                sum--;
            }
        });
    } while (sum > 0 && map.get("Strength") <= MAX_VALUE);

    //...rest

答案 3 :(得分:0)

您可以使用一个简单的数组和一个for循环:

public class RandomStatsGenerator {

    int[] attributes = {3, 3, 3, 3, 3, 3};
    int sum = 45;
    static final int MAX_VALUE = 18;

    public void generate() {
        for (int i = 0; sum != 0; i++) {
            boolean test = getRandomBoolean();
            if (test == true && attributes[i] <= MAX_VALUE) {
                attributes[i]++;
                sum--;
            }
            if ( i == 5 ) {
                i = -1;
            }
        }
        System.out.println("Strength: " + attributes[0] + ".");
        System.out.println("Dexterity: " + attributes[1] + ".");
        System.out.println("Constitution: " + attributes[2] + ".");
        System.out.println("Intelligence: " + attributes[3] + ".");
        System.out.println("Wisdom: " + attributes[4] + ".");
        System.out.println("Charisma: " + attributes[5] + ".");
    }
}

然后,如果您仍然希望将属性用作包专用变量,则可以在使用数组中的值设置它们之后定义它们。