【问题标题】:negative number not going into int负数不进入 int
【发布时间】:2014-02-24 08:23:14
【问题描述】:

我在 java 中有以下代码。在这里,我试图查看数组的随机组合。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class Dummy {
    public static void main(String args[]) throws Exception {
        Random rand = new Random();

        int[] a = { 1, 2, 3, 4, 5 };
        int[] b = { 1, 0, 1, 0, 1 };
        Arrays.sort(a);
        Arrays.sort(b);
        int x = a.length * b.length;
        System.out.println(x);

        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 25; i++) {

            System.out.println("random of i is" + a[rand.nextInt(i)]
                    + "and j is " + b[rand.nextInt(i)]);

        }
        System.out.println(list);

    }
}

这里我收到以下错误。

Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
    at java.util.Random.nextInt(Unknown Source)
    at Dummy.main(Dummy.java:20)

请告诉我如何解决它。基于类似问题的其他一些帖子,我发现随机只能给出正数,我想知道如何也可以给出负数。

我还想知道通过延续 a[] 和 b[] 可以获得多少种组合。

谢谢

【问题讨论】:

  • 来自文档:if (n &lt;= 0) throw new IllegalArgumentException("n must be positive"); 在您的第一次迭代中i 的值是多少?
  • ypu 的意思是“我可以通过永久 a[] 和 b[] 获得多少组合”?
  • @ZouZou:这里的迭代,在0到25之间,第一次迭代是1
  • @user2423959 在您的第一次迭代中,i 的值是 0,而不是 1。
  • 好的,谢谢帮助:-)

标签: java random arraylist


【解决方案1】:

您的error 是因为您在rand.nextInt(i) 中传递了0。

rand.nextInt() expects positive integer greater that 0.

【讨论】:

    【解决方案2】:

    您正在循环最大为 25 和 0 的数组,

    将最大值改为数组的大小,然后初始化大于零的i 否则你会得到ArrayIndexOutOfBoundsException

    这样做

    for (int i = 1; i <= a.length; i++) {
    
                System.out.println("random of i is" + a[rand.nextInt(i)]
                        + "and j is " + b[rand.nextInt(i)]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 2015-04-17
      • 1970-01-01
      • 2011-02-17
      • 2018-09-07
      相关资源
      最近更新 更多