【问题标题】:Using string-array list length as an integer使用字符串数组列表长度作为整数
【发布时间】:2011-02-13 20:48:56
【问题描述】:

我正在使用随机数生成器从 Android 字符串数组中选择一个项目。有没有办法将我的整数设置为数组的长度而不实际计算数组中的项目数?

这是我正在使用的随机数代码示例:

private Random random = new Random();
private int n = random.nextInt(4);

private String randText;

public Object(Context contex)
{
String[] string = context.getResources().getStringArray(R.array.text);

randText = "Stuff to display " + string[n] +".";
}

public String getRandText
{
return randText
}

我想将上面的“4”定义为特定数组列表的长度。有人知道怎么做吗?

【问题讨论】:

    标签: java android random arrays


    【解决方案1】:

    我想将上面的“4”定义为特定数组列表的长度。

    也许这就是你所追求的:

    String[] strs = { "str1", "str2", "str3", "str4", "str5" };
    
    // Select a random (valid) index of the array strs
    Random rnd = new Random();
    int index = rnd.nextInt(strs.length);
    
    // Print the randomly selected string
    System.out.println(strs[index]);
    

    要访问实际的数组,请执行以下操作:

    Resources res = getResources();
    String[] yourStrings = res.getStringArray(R.array.your_array);
    

    (然后要获取数组中的元素个数,请执行yourStrings.length。)


    关于您的编辑。试试这个:

    private Random random = new Random();
    private int n; // Can't decide up here, since array is not declared / initialized
    
    private String randText;
    
    public YourObject(Context contex) {
        String[] string = context.getResources().getStringArray(R.array.text);
        n = random.nextInt(string.length);     // <--- Do it here instead.
        randText = "Stuff to display " + string[n] +".";
    }
    
    public String getRandText {
        return randText;
    }
    

    【讨论】:

    • 我在这里专门谈论Android,所以我在strings.xml中有一个字符串数组,我正在访问......我没有在我的代码中声明一个数组,只是访问Android资源——所以我正在寻找访问该资源的语法(strings.xml 中的字符串数组)。
    • 那么它应该是一个普通的Java数组,你应该能够按照我的回答中的建议使用arrayName.length获取元素的数量。
    • 这也是我最初的想法,但是当我尝试时,Eclipse 报错“arrayName 无法解析为变量。”
    • 你是如何声明变量的? (需要在前面加上String[]!)
    • 我确实使用了 String[]... 不过它在一个类中,不知道这是否是问题所在。等一下,会提供更多我的代码。
    【解决方案2】:
    List myList = ...
    int n = select.nextInt(myList.size());
    

    【讨论】:

    • 我在这里专门谈论 Android,所以我在 strings.xml 中有一个字符串数组,我正在访问...我没有在我的代码中声明一个数组列表,只是访问Android 资源——所以我正在寻找访问该资源的语法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多