您的位置 首页 java

Java数组案例

Java数组

描述

获取 Java 数组 中的数据并进行运算。

题目

创建一个长度为 6 的 整数 数组,随机生成六个 0 (包含) – 100 (不包含) 之间的整数存放到数组中,然后计算出数组中所有元素的和并打印。

题目解决思路

  1. 定义长度为 6 的数组。
  2. 创建随机数 Random 类对象。
  3. 遍历数组 ,在循环中生成随机数并给数组元素赋值。
  4. 定义求和变量,初始化值为 0。
  5. 遍历数组,获取每一个元素,累加。
  6. 遍历结束,打印结果。

代码具体实现

 import java.util.Random;

public class ArrayDemo03 {
    public static void main(String[] args) {
        System.out.println("嗨客网(www.haicoder.net)n");

        // 定义长度为 6 的数组
        int [] arr1 = new int [6];
        // 定义变量存储计算结果
        int sum = 0;
        // 创建随机数Random类对象
        Random random = new Random();
        // 遍历数组,在循环中生成随机数并给数组元素赋值
        for(int i = 0; i < 6;i++){
            arr1[i] = random.nextInt(100);
        }
        System.out.print("数组中的元素分别为:");
        // 遍历数组,获取每一个元素,累加
        for(int j = 0; j < arr1.length; j++){
            System.out.print(arr1[j] + " ");
            sum += arr1[j];
        }
        System.out.println("");
        // 遍历结束,打印结果
        System.out.println("数组元素的和为:" + sum);
    }
}  

运行结果如下图:

Java数组案例

以上代码实现存储 6 个随机数到数组中,并计算出它们的和。

文章来源:智云一二三科技

文章标题:Java数组案例

文章地址:https://www.zhihuclub.com/174926.shtml

关于作者: 智云科技

热门文章

评论已关闭

5条评论

  1. Alternatively, the nodes may be assessed using conventional pathologic methods, followed by the radical trachelectomy as a second surgery 1 week later 26

  2. Hmm is anyone else experiencing problems with the images on this blog loading 70 In contrast, NSABP protocol B16 shows benefit for tamoxifen treated postmenopausal patients with the addition of an Adriamycin containing chemotherapy regimen

  3. This exploratory review has outlined a gap in the literature regarding opioid consumption and other postoperative benefits following TAP block analgesia in pancreaticoduodenectomy patients

网站地图