import java.util.Arrays;
import java.util.Scanner;
public class LotteryDrawing {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers dou you want to draw?");
int k = input.nextInt();
System.out.println("What's the highest number can you draw?");
int n = input.nextInt();
int [] numbers = new int [n];
int [] result = new int [k];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i+1;
}
for (int i = 0; i < result.length; i++) {
int r = (int)(Math.random()*n);
result[i] = numbers[r];
numbers[r] = numbers[n-1];
n--;
}
Arrays.sort(result);
System.out.println("Bet the following combination.It'll make you rich!");
for(int x : result){
System.out.println(x);
}
}
}
java
int [] numbers = new int [n];int [] result = new int [k];
numbers[r] = numbers[n-1];
先是定义了numbers的长度为n 然后你要递减的去给numbers[r]赋值为numbers[n-1],当K的长度大于n的时候就会出现n=0的情况,numbers[-1]当然就数组越界了n与k是你自己输入的数字。所以会有小的bug1.保证输入时k<n
2.判断n=0是下面的循环就break了。