|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import java.util.Arrays;
import java.util.Scanner;
public class LotteryDrawing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("how many numbers do you need to draw?");
int k = in.nextInt();
System.out.print("what is the highest number you can draw?");
int n = in.nextInt();
int[] number = new int[n];//建立一个新的数组
for (int i = 0; i < number.length; i++)
number[i] = i + 1;
int[] result = new int[k];
for (int i = 0; i < result.length; i++) {
//建立一个0~n-1之间的索引值
int r = (int) (Math.random() * n);
result[i] = number[r];
number[r] = number[n - 1];
n--;
}
Arrays.sort(result);
System.out.print("bet the following combination,It'll make you rich");
for (int r : result)
System.out.println(r);
}
}
这是控制台的输出信息:
how many numbers do you need to draw?100
what is the highest number you can draw?10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
at New.LotteryDrawing.main(LotteryDrawing.java:26)
Process finished with exit code 1
出错的代码为我标红的那一个,我这个是按照书上输入的,在给定的K个数字中随机抽取n个数字输出,求大佬帮忙看一下,代码如何修改才可以运行。
本帖最后由 小伤口 于 2022-1-13 20:33 编辑
你输入的100是k,也就是for循环会循环100次,而你的n只有10,所以n--在for循环10次之后就变成负数,就溢出了,
会不会是你初始化数组n和k写反了  ,我有点没搞懂这个题目,不过这样的确可以正常运行
- import java.util.Arrays;
- import java.util.Scanner;
- public class FamilyAccount {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- System.out.print("how many numbers do you need to draw?");
- int k = in.nextInt();
- System.out.print("what is the highest number you can draw?");
- int n = in.nextInt();
- int[] number = new int[k];//建立一个新的数组
- for (int i = 0; i < number.length; i++)
- number[i] = i + 1;
- int[] result = new int[n];
- for (int i = 0; i < result.length; i++) {
- //建立一个0~n-1之间的索引值
- int r = (int) (Math.random() * n);
- result[i] = number[r];
- number[r] = number[n - 1];
- n--;
- }
- Arrays.sort(result);
- System.out.print("bet the following combination,It'll make you rich");
- for (int r : result)
- System.out.println(r);
- }
- }
复制代码
|
|