【问题标题】:String Array only returns one string in android字符串数组在android中只返回一个字符串
【发布时间】:2013-10-10 08:12:49
【问题描述】:

我正在尝试在 textView 对象中显示一个字符串。 目前我只得到字符串数组中的第一个字符串。

   public void onClick(View v) {
        Resources res = getResources();
        String[] hintsStr = res.getStringArray(R.array.hints);
        TextView hintShow = (TextView)findViewById(R.id.hintShow);
        int rndInd = (int) Math.random()*5;
        //hintShow.setText(rndInd);
        hintShow.setText(hintsStr[rndInd]);
        //System.out.print(rndInd);
    }

【问题讨论】:

    标签: java android string random


    【解决方案1】:

    试试这个来生成你的随机数。-

    Random rand = new Random();
    int rndInd = rand.nextInt(5); // Will get a rand number between 0 and 4
    

    另外,您应该只将 rand 对象实例化一次,作为onClick 方法之外的实例变量。

    【讨论】:

      【解决方案2】:

      您将 Math.rand() 的结果转换为 int,因此结果始终为 0,您可以执行 int rndInd = (int)(Math.random()*5); 甚至更好地使用 ssantos 建议的解决方案

      【讨论】:

        【解决方案3】:

        先初始化随机类,再取值,代码如下

        Randon random=new Random();
        int value = random.nextInt(10);
        

        它肯定会起作用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-09
          • 2013-04-18
          • 2014-12-18
          • 2012-01-22
          • 1970-01-01
          • 2011-11-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多