gpt4 book ai didi

java - 如何从字符串数组列表中随机选择

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:04 24 4
gpt4 key购买 nike

我有一个字符串数组列表:

<string-array name="chapter_1">
<item>......</item>
.
.
.
.
</string-array>

<string-array name="chapter_2">
<item>......</item>
.
.
.
.
</string-array>

等等。我有一个随机整数 chapter_no。

我有一个字符串:

String chapter_name = "chapter_" + chapter_no;

现在,我想访问与 chapter_no 对应的字符串数组。

我知道我不能这样做:

String[] chapter = getResources().getStringArray(R.array.chapter_name);

如何随机访问字符串数组?请帮助我。

最佳答案

从 chapter_array 获取随机字符串 ..

String[] chapter = getResources().getStringArray(R.array.chapter_name);

String randomString = chapter[new Random(chapter.length).nextInt()];

[更新]

        String[] data;

//first of all give all resources to arrays
int[] arrays = {R.string.chapter_1, R.string.chapter_2};

//then we are fetching any one string array resources randomly
int chapter_no = arrays[new Random(arrays.length).nextInt()];

//From above we got any one random resource string..So we fetch all string items from that resource into data array
data = getResources().getStringArray(chapter_no);

//Now from that data array we fetch any one random string.
String randomString = data[new Random(data.length).nextInt()];

[更新]

    String[] data;
int[] arrays = {R.array.chapter_1, R.array.chapter_2};
int chapter_no = arrays[new Random().nextInt(arrays.length-1)];
data = getResources().getStringArray(chapter_no);
String randomString = data[new Random().nextInt(data.length-1)];
Toast.makeText(this, randomString, Toast.LENGTH_SHORT).show();

关于java - 如何从字符串数组列表中随机选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30756262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com