当前位置:网站首页>数组静态初始化,遍历,最值
数组静态初始化,遍历,最值
2022-07-25 09:27:00 【anerl】
数组静态初始化
一、静态初始化
静态初始化:初始化时指定每个数组元素的初始值,由系统决定数组的长度。
格式:数据类型[ ] 变量名 = new 数据类型[ ] {数据1,数据2,数据3,........}
范例:数据类型 [ ] 变量名 = {数据1,数据2,数据3,.....}
简化格式:数据类型 [ ] 变量名 = {数据1,数据2,数据3,....}:
代码示例:
public class ArrayTest {
public static void main(String[] args) {
//定义数组
int[] arr = {
1,2,3};
//输出数组名
System.out.println(arr);
//输出数组中的元素
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
}
}
二、数组操作中的两个常见问题
索引越界:访问了数组中不存在的索引对应的元素,造成索引越界问题。
空指针异常:访问的数组已经不再指向堆内存的数据,造成空指针异常
null:空值,引用数据类型的默认值,表示不指向任何有效对象。
三、数组遍历
获取数组中的元素个数:数组名.length 如:arr.length
代码示例:
public class ArrayTest01 {
public static void main(String[] args) {
//定义数组
int[] arr = {
11,22,33,44,55};
//使用通用遍历格式
for (int i=0;i< arr.length;i++){
System.out.println(arr[i]);
}
}
}
四、获取最值
1.定义一个变量,用于保存最大值(或最小值)2.获取数组中第一个数据作为变量的初始值3.与数组中剩余的数据逐个对比
代码示例(最小值同理):
public class ArrayTest02 {
public static void main(String[] args) {
//定义数组
int[] arr = {
12,45,98,73,60};
//定义一个变量,用于保存最大值(或最小值)`
//获取数组中第一个数据作为变量的初始值`
int max = arr[0];
//与数组中剩余的数据逐个对比,每次对比将最大值保存到变量中
for (int i=1;i< arr.length;i++){
if (arr[i] >max){
max=arr[i];
}
}
//循环结束后打印变量的值
System.out.println("max:"+max);
}
}
边栏推荐
- [necessary for growth] Why do I recommend you to write a blog? May you be what you want to be in years to come.
- VSCode Latex Workshop 设置 XeLatex 编译
- TCP传输
- UE4 框架介绍
- MVC three-tier architecture understanding
- cookie and session
- 第五阶段第一周
- 数论---最大公约数最小公倍数
- Detailed explanation of JDBC operation database
- Configuring ROS development environment with vscode: Causes and solutions to the problem of ineffective code modification
猜你喜欢

静态路由的配置(以华为eNSP为例)

message from server: “Host ‘xxx.xxx.xxx.xxx‘ is not allowed to connect to this MySQL server“

UE4 框架介绍

@Import,Conditional和@ImportResourse注解

小程序H5获取手机号方案

Pow(x,n)

小程序企业发放红包功能

【专栏】RPC系列(理论)-夜的第一章

Configuring ROS development environment with vscode: Causes and solutions to the problem of ineffective code modification

史上最全面的UE4 文件操作,打开,读、写,增、删、改、查
随机推荐
C3D模型pytorch源码逐句详析(三)
UE4源码的获取和编译
JDBC操作数据库详解
Debug篇快捷键入门
多线程——死锁和synchronized
The way of code neatness -- hit the pain point directly
语音自监督预训练模型 CNN Encoder 调研总结
JSP details
将 conda 虚拟环境 env 加入 jupyter kernel
车辆属性最近一次入库时间初始化生成sql脚本文件
Probabilistic robot learning notes Chapter 2
oh-my-zsh和tmux配置(个人)
小程序分享功能
vscode插件开发
用户喜好
The first week of the fifth stage
Trojaning Attack on Neural Networks 论文阅读笔记
贪吃蛇小游戏
CentOs安装redis
几个常用的网络诊断命令