动态数组for循环生成有范围的数,超出范围 提示重新循环 并重新输入第一位数怎么做啊

public static int[] userInputNumbers(){
// a、定义一个动态初始化数组,存储 7个数字
int[] numbers = new int[7];
// b、让用户录入 6个红球号码
Scanner sc = new Scanner(System.in);
for (int i = 0; i < numbers.length - 1; i++) {
System.out.println(“请您输入第”+ (i+1) + “个红球号码(1-33),要求不重复:”);
int data = sc.nextInt();
// c、把当前录入的数据存到数组中去
numbers[i] = data;
}
// d、单独录入一个蓝球号码
System.out.println(“请您输入最后一位蓝球的号码(1-16):”);
numbers[6] = sc.nextInt();
return numbers;
}
// 谢谢,试过用if判断 但是并不会重新循环,刚在学完方法

讨论数量: 2

思路参考 不使用无限循环 使用循环变量进行控制 如果你想重新循环 将变量重新初始化即可 附上以前写的一个辅助类

    /**
     * 随机多选不重复的数据
     * @param sources 数据源
     * @param selectSources 选择的数据
     */
    public void randomSources(T[] sources, T[] selectSources){
        for (int i = 0; i < selectSources.length; ++i) {
            selectSources[i] = randomSource(sources);
            for (int j = 0; j < i; ++j) {
                if(Objects.equals(selectSources[i], selectSources[j])) {
                    i--;
                    break;
                }
            }
        }
    }

    /**
     * 随机单选
     * @param sources 数据源
     * @return 返回选中数据
     */
    public T randomSource(T[] sources){
        return sources[ran.nextInt(sources.length)];
    }
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!