• Java


    生成1个长度为10的存储int类型元素的数组,以随机的方式为数组元素赋值其值不得重复,能够打印其中最大的数组元素的值和索引。

    Main文件

    import java.util.Random;
    
    public class Main {
    
        public static void main(String[] args) {
            int array[];
            array = new int[10];
    
            p:for(int i = 0; i < 10;){        // 表达式 3 为空
                int value = make_random();    // 生成随机数
                for(int m = 0; m < i; m++){   // 判断是否有重复
                    if(value == array[m]){    // 如果有重值
                        continue p;           // 进行  p语块  下一次循环
                    }
                }
                array[i] = value;   // 给数组赋值
                i++;                // 数组下标值 + 1
            }
    
            ArrayMessage(array);    // 输出随机生成的数组
            Max_And_Min(array);     // 输出最大值和其索引
        }
        
        /**
         * 生产随机数
         * @return
         */
        public static int make_random(){
            Random rnd = new Random();    // 实例化一个对象
            int tmp = rnd.nextInt(10);    // 生成100以内的随机数
            return tmp;                   // 返回随机数
        }
        
        /**
         * 输出数组信息
         * @param array
         */
        public static void ArrayMessage(int array[]){
            System.out.print("生成的随机数组为:
    [");
            for(int i = 0; i < 9; i++){
                System.out.print(array[i] + ",");
            }
            System.out.println(array[9] + "]");
        }
    
        /**
         * 输出数组的最大值及其索引
         * @param array
         */
        public static void Max_And_Min(int array[]){
            int max = array[9];             // 定义最大值的初值为数组的任一个元素,这样可以减少比较次数
            int mark = 9;                   // 定义最大值的索引初值为该元素的索引;
            for(int i = 0; i < 10; i++){    // 遍历数组的所有
                if(array[i] >= max){        // 如果某个元素大于等于最大值
                    max = array[i];         // 把该元素的设为最大值
                    mark = i;               // 把该元素的索引赋给mark
                }
            }
            System.out.print("其中数组元素的最大值为:" + max + " , 索引为:" + mark);
        }
    }
  • 相关阅读:
    牛客网-湘潭大学校赛重现H题 (线段树 染色问题)
    bzoj 2243: [SDOI2011]染色 (树链剖分+线段树 区间合并)
    SPOJ QTREE2 (LCA
    Neo4j-Cypher
    MySQL避免插入重复记录:唯一性约束
    python ftp教程
    Neo4j 导入 CSV 文件
    jupyter notebook 安装 jupyter_contrib_nbextension
    python 性能分析(时间,空间)之 line_profiler 模块 ,memory_profiler的使用
    hive 自定义函数
  • 原文地址:https://www.cnblogs.com/humingx/p/4185005.html
Copyright © 2020-2023  润新知