【问题标题】:How to find random element matching to condition in a table?如何在表中找到与条件匹配的随机元素?
【发布时间】:2018-08-29 19:53:15
【问题描述】:

我已经制作了一个带有几何图形的表格和一个 for 循环,用于打印出具有直角的图形的名称,但我想为该图形打印一个符合条件的随机名称,如果可以创建另一个表只包含符合条件的数字。我试图使用java.util.Random 中的一些方法,但我不知道怎么做。我会感谢你的帮助:

import java.util.Random;

public class rectangularFigures {
    private String name;
    private boolean rightAngle;

    public String getName() {
        return name;
    }

    public rectangularFigures(String name, boolean rightAngle) {
        this.name = name;
        this.rightAngle = rightAngle;
    }

    public static void main(String[] args) {
        rectangularFigures[] lOFigures = new rectangularFigures[4];

        lOFigures[0] = new rectangularFigures("whell", false);
        lOFigures[1] = new rectangularFigures("square", true);
        lOFigures[2] = new rectangularFigures("rhombus", false);
        lOFigures[3] = new rectangularFigures("rectangle", true);

        for (int i = 0; i < lOFigures.length; i++) {
            {
                if (lOFigures[i].rightAngle) {
                    System.out.println(lOFigures[i].name);
                }
            }
        }
    }
}

【问题讨论】:

  • 如果你想要尽可能随机的东西,我知道在 java 中的最佳选择是使用 SecureRandom,它是一个适用于加密应用程序的随机数生成器,例如查看来自 @ 的示例 4 987654322@

标签: java loops conditional-statements


【解决方案1】:

最简单的方法是使用java流:

rectangularFigures[] onlyRightAngles = Arrays.stream(lOFigures).filter(x -> x.rightAngle).toArray(rectangularFigures[]::new);
    rectangularFigures randomElement = onlyRightAngles[new Random().nextInt(onlyRightAngles.length)];
    System.out.println(randomElement.name);

但是如果由于某些原因你不能使用流,我建议使用 ArrayList 和传统的 foreach 循环:

List<rectangularFigures> onlyRightAngles = new ArrayList<>();
    for (rectangularFigures figure : lOFigures) {
        if (figure.rightAngle) onlyRightAngles.add(figure);
    }
    rectangularFigures randomElement = onlyRightAngles.get(new Random().nextInt(onlyRightAngles.size()));
    System.out.println(randomElement.name);

【讨论】:

    【解决方案2】:

    这只是一个小例子,但可以改进:

        Random r = new Random();
    
        for (int i = 0; i < lOFigures.length; i++) {
            {
                int f = r.nextInt(4);
                if (lOFigures[f].rightAngle) {
                    System.out.println(lOFigures[f].name);
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2021-12-19
      • 2012-11-19
      • 2022-01-16
      • 2020-02-23
      相关资源
      最近更新 更多