初识数组

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

数组的创建和赋值

创建:

  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+" ");
        }
    }
}

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

相关推荐
技术猿1887027835129 分钟前
Java、PHP、C++ 三种语言实现爬虫的核心技术对比与示例
java·c++·php
韩占康36 分钟前
没想到Java ThreadLocal 知识点居然这么多
java
用户5903363605937 分钟前
Aware"感知"接口
java
小码编匠39 分钟前
基于 SpringBoot 开源智碳能源管理系统(EMS),赋能企业节能减排与碳管理
java·后端·开源
booooooty1 小时前
【Java项目设计】基于Springboot+Vue的OA办公自动化系统
java·vue.js·spring boot·毕业设计·课程设计·程序开发
白云如幻1 小时前
【Java】HQL分页查询
java·hibernate
小猫咪怎么会有坏心思呢1 小时前
华为OD机考-观看文艺汇演问题-区间问题(JAVA 2025B卷)
java·jvm
Java初学者小白2 小时前
秋招Day14 - MySQL - SQL优化
java·数据库·sql·mysql
Cyanto2 小时前
Tomcat双击startup.bat闪退的解决方法
java·tomcat
武昌库里写JAVA3 小时前
Vue状态管理实践:使用Vuex进行前端状态管理
java·vue.js·spring boot·课程设计·宠物管理