Java数组问题
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;//建立一个新的数组
for (int i = 0; i < number.length; i++)
number = i + 1;
int[] result = new int;
for (int i = 0; i < result.length; i++) {
//建立一个0~n-1之间的索引值
int r = (int) (Math.random() * n);
result = number;
number = number;
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个数字输出,求大佬帮忙看一下,代码如何修改才可以运行。 题目真的是这个意思吗,我感觉有点对不上呀{:9_231:} 本帖最后由 小伤口 于 2022-1-13 20:33 编辑
你输入的100是k,也就是for循环会循环100次,而你的n只有10,所以n--在for循环10次之后就变成负数,就溢出了,
会不会是你初始化数组n和k写反了{:9_237:},我有点没搞懂这个题目,不过这样的确可以正常运行
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;//建立一个新的数组
for (int i = 0; i < number.length; i++)
number = i + 1;
int[] result = new int;
for (int i = 0; i < result.length; i++) {
//建立一个0~n-1之间的索引值
int r = (int) (Math.random() * n);
result = number;
number = number;
n--;
}
Arrays.sort(result);
System.out.print("bet the following combination,It'll make you rich");
for (int r : result)
System.out.println(r);
}
} {:10_256:} {:10_256:} 小伤口 发表于 2022-1-13 20:30
你输入的100是k,也就是for循环会循环100次,而你的n只有10,所以n--在for循环10次之后就变成负数,就溢出 ...
谢谢大佬 {:5_95:} {:10_279:} {:10_256:} {:10_254:} yes
{:10_256:} {:10_279:} {:10_257:}{:10_257:} {:5_109:} {:10_257:} {:9_222:} {:5_95:} {:10_279:} {:10_279:}
页:
[1]
2