【问题标题】:App crashing when chosing random numbers to select array index [closed]选择随机数以选择数组索引时应用程序崩溃[关闭]
【发布时间】:2015-08-17 07:10:56
【问题描述】:

编辑:已解决。这是一个愚蠢的错误!感谢您的快速响应。 我有 6 个数组,每个数组有 150-200 个元素。现在,当我尝试选择索引号时,前两个选择得很好,但是从第三个索引号开始,应用程序开始崩溃。应用只有一项活动。

String A[]={};
String B[]={};
...
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public void generate(View v) {
    tToast("Insult on your beep!");
    Gener();
}

public void Gener()
{

    int i1 = new Random().nextInt(A.length);
    String r1 = (A[i1]);

    int i2 = new Random().nextInt(B.length);
    String r2 = (A[i2]);

    int i3 = new Random().nextInt(C.length);
    String r3 = (A[i3]);

    int i4 = new Random().nextInt(D.length);
    String r4 = (A[i4]);

    int i5 = new Random().nextInt(E.length);
    String r5 = (A[i5]);

    int i6 = new Random().nextInt(F.length);
    String r6 = (A[i6]);

    String fin = r1 + r2 +r3 + r4 +r5 +r6;
    //Works OK up to r2 but from r3 error occurs
    final TextView mTextView = (TextView) findViewById(R.id.Gen);
    mTextView.setText(fin);
    tToast("Me works");
}
private void tToast(String s) {
    Context context = getApplicationContext();
    int duration = Toast.LENGTH_LONG;
    Toast toast = Toast.makeText(context, s, duration);
    toast.show();
}

【问题讨论】:

  • 我无法提供这些数组,因为它们包含敏感信息。
  • LogCat 说了什么?
  • 发布您遇到的错误
  • 使用 StringBuilder 连接可能出错的多个字符串

标签: java android arrays random


【解决方案1】:

您每次都从A 数组中选择字符串。我假设您想为每个字符串从每个不同的数组中进行选择。

示例

您的代码: String r5 = (A[i5])

我猜你想要什么:

String r5 = (E[i5])

【讨论】:

    【解决方案2】:

    您正在计算从 A 到 F 的每个数组的随机索引,但试图从 A 数组中获取索引的值。所以这可能会导致 ArrayIndex 异常尝试像这样更改您的代码

    int i1 = new Random().nextInt(A.length);
    String r1 = (A[i1]);
    
    int i2 = new Random().nextInt(B.length);
    String r2 = (B[i2]);
    
    int i3 = new Random().nextInt(C.length);
    String r3 = (C[i3]);
    
    int i4 = new Random().nextInt(D.length);
    String r4 = (D[i4]);
    
    int i5 = new Random().nextInt(E.length);
    String r5 = (E[i5]);
    
    int i6 = new Random().nextInt(F.length);
    String r6 = (F[i6]);
    
    //Remaining code....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-12
      • 1970-01-01
      • 2021-12-16
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多