初识数组

数组的大概内容(自学)上篇

数组的创建和赋值

创建:

  1. int \[\] name = new int 5;

  2. int name \[\] = new int 5;

  3. int \[\] name = {1,2.3,4,5};

赋值:

  1. int \[\] score = {1,2,3};

  2. int \[\] score = new int \[\] {1,2,3};

  3. int \[\] score;//声明

    score = new int \[\]{1,2,3};

键盘赋值
复制代码
package shuzu;
​
import java.util.Scanner;
​
public class shuZuDemo01 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int [] scores = new int [3];
        for (int i = 0; i < scores.length; i++) {
            scores[i] = input.nextInt();
        }
    }
}

数组的遍历

复制代码
package shuzu;
//数组的遍历
public class shuZuDemo02 {
    //定义一个方法
    public static void print(int [] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
    public static void main(String[] args) {
        int [] arr = new int []{1,2,3,4,5};
        print(arr);
        System.out.println();
        //加强for便利更简洁
        int [] arr1 = new int []{1,2,3,4,5,6,7,8,9};
        for (int x : arr1) {
            System.out.print(x + " ");
        }
​
    }
}

最值问题

复制代码
package shuzu;
​
public class shuZuDemo03 {
    public static void main(String[] args) {
        int [] arr = {1,2,3,4,5,6,7,8,9,10};
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        System.out.println(max);
    }
}

排序算法

冒泡排序

复制代码
package shuzu;
​
public class shuZuDemo04 {
    public static void main(String[] args) {
        int[] arr = {25, 2, 350, 4, 11, 5, 6, 99, 9};
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        for (int x : arr) {
            System.out.print(x+" ");
        }
    }
}

打卡!打卡!打卡!打卡!打卡!

相关推荐
晨曦中的暮雨10 小时前
限流算法——固定窗口、滑动窗口、漏桶、令牌桶
java·开发语言·算法
文丑颜不良啊11 小时前
LeetCode876~900题目解析
java·leetcode
aloha_78912 小时前
Java 基础、集合、异常与 JUnit 5 速查
java·junit·sqlserver
知守观12 小时前
设计模式实战:从真实老项目中看标准模板方法与工厂的落地
java·spring·设计模式
独隅12 小时前
Claude API 实战教程:从入门到完整项目
android·java·数据库·claude·claude code
Wang's Blog13 小时前
Java 项目实战: 交友项目 - 圈子功能实现:总结
java·开发语言·交友
SL_staff13 小时前
JVS私有化文档系统上线避坑指南:5大运维与业务协同断点及检测加固实践
java·开源·全栈
FinelyYang14 小时前
考试系统简答题 AI 阅卷:覆盖度驱动、异步评分与人机协同落地实践
java·大数据·人工智能
hhhjhl14 小时前
Yup 跨端三方库仓颉适配全流程
java·开发语言
用户31268748772015 小时前
Java 对象内存布局:压缩指针、对齐填充与 JOL 实测
java