Ang*_*elo 1 java string random final
正如问题所说,我在最后一堂课中有多个决赛字符串,如下所示:
public final class MyStrings {
public static final String stringOne = "this is string one";
public static final String stringTwo = "this is string two";
public static final String stringThree = "this is string three";
public static final String stringFour = "this is string four";
public static final String stringFive = "this is string five";
}
Run Code Online (Sandbox Code Playgroud)
我知道将它们放在列表或数组中会更容易,但我想避免运行时填充这些结构.可能吗?从该类中随机选择字符串的最简单方法是什么?谢谢.
你String似乎非常相关,因为你有一个需要随机选择其中一个的用例.因此,无论如何它们应该被聚集在一个数组中(从语义的角度来看).
没有比当前多个字段更多的"运行时填充":
public final class MyStrings {
public static final String[] strings = {
"this is string one",
"this is string two",
"this is string three",
"this is string four",
"this is string five"
};
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样String随机选择一个:
Random random = new Random();
String randomString = strings[random.nextInt(strings.length)]);
Run Code Online (Sandbox Code Playgroud)
String[] mystring = {
"this is string one",
"this is string two",
"this is string three",
"this is string four",
"this is string five"
};
int idx = new Random().nextInt(mystring.length);
String random = (mystring [idx]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2674 次 |
| 最近记录: |