Android - 生成随机数的崩溃

时间:2012-11-04 00:11:36

标签: java android random runtime-error

所以,我已经查看了其他地方如何生成随机数,并将其放入Android应用程序中。我希望这可行,但遗憾的是,它崩溃了这个LogCat:

11-03 17:06:48.930: W/dalvikvm(8327): threadid=1: thread exiting with uncaught exception (group=0x41ff0300)
11-03 17:06:48.938: E/AndroidRuntime(8327): FATAL EXCEPTION: main
11-03 17:06:48.938: E/AndroidRuntime(8327): java.lang.IllegalArgumentException
11-03 17:06:48.938: E/AndroidRuntime(8327):     at java.util.Random.nextInt(Random.java:187)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at com.spng453.randomnum.RandomNumber$1.onClick(RandomNumber.java:24)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at android.view.View.performClick(View.java:4084)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at android.view.View$PerformClick.run(View.java:16966)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at android.os.Handler.handleCallback(Handler.java:615)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at android.os.Looper.loop(Looper.java:137)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at java.lang.reflect.Method.invokeNative(Native Method)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at java.lang.reflect.Method.invoke(Method.java:511)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 17:06:48.938: E/AndroidRuntime(8327):     at dalvik.system.NativeStart.main(Native Method)
11-03 17:06:51.376: I/Process(8327): Sending signal. PID: 8327 SIG: 9

我已经尝试了一切我能想到的东西让它发挥作用,但没有做到。这是代码:

private OnClickListener Gen = new OnClickListener() {
    public void onClick(View v) {
        Random rand;
        rand = new Random();
        EditText maxin = (EditText)findViewById(R.id.max);
        EditText minin = (EditText)findViewById(R.id.min);
        TextView out = (TextView)findViewById(R.id.out);
        int max = Integer.parseInt(maxin.getText().toString().trim());
        int min = Integer.parseInt(minin.getText().toString().trim());
        out.setText(Integer.toString(rand.nextInt(max-min) + min));
    }
};

2 个答案:

答案 0 :(得分:4)

好吧,如果您的max文本框的数字小于或等于min文本框,则肯定会发生这种情况。您应该在致电Random.nextInt(int)之前对其进行验证。正如文档所述:

  

<强>抛出:
  IllegalArgumentException - 如果n不是正数

当然,您应该处理文本框中根本没有有效数字的情况。

最后,有没有理由为什么你要分离rand的声明和作业?

Random rand;
rand = new Random();

为什么不呢:

Random rand = new Random();

答案 1 :(得分:1)

java.lang.IllegalArgumentException表示您向您nextInt()函数传递了非法参数。我猜你的论点不那么零,或类似的东西。检查调试器中的这些值以确保您的参数有效。