选择随机 Java 变量?这可能吗 [英] Select random Java variable? Is this possible

查看:58
本文介绍了选择随机 Java 变量?这可能吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下设置:

private String one = "abc";
private String two = "def";
private String three = "ghi";

我想编写一个返回随机变量的方法,这是我在类的顶部声明的许多方法之一.有没有简单的方法可以做到这一点?

I want to write a method that returns a random variable, one of the however many I have declared at the top of the class. Is there an easy way to do this?

推荐答案

这个简单的方法怎么样?或者,如果元素过多,则使用 Collection 来完成.

What about this simple method? Or do it with a Collection if you have too many elements.

public String getRandomString(){
        Random r = new Random();

        int i = r.nextInt()%3;

        switch (i) {
            case 0:
                return one;
            case 1:
                return two;
            case 2:
                return three;
            default:
                break;
        }

    }

这篇关于选择随机 Java 变量?这可能吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆