[英]negative number not going into int
我在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)
請讓我知道如何解決它。 根據基於相似問題的其他一些帖子,我發現只有正數才會給出隨機數,我想知道我怎樣才能給出負數。
此外,我想知道通過延續[]和b []可以獲得多少組合。
謝謝
您的error
是因為您在rand.nextInt(i)
中傳遞了0。
rand.nextInt() expects positive integer greater that 0.
你循環數組最多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)]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.