您当前的位置: 首页 >  Java

川川菜鸟

暂无认证

  • 1浏览

    0关注

    969博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java数组

川川菜鸟 发布时间:2021-11-02 22:23:27 ,浏览量:1

文章目录
    • Java 数组定义
    • 访问数组的元素
    • 更改数组元素
    • 数组长度
    • 循环遍历数组

Java 数组定义

数组用于在单个变量中存储多个值,而不是为每个值声明单独的变量,要声明数组,请使用方括号定义变量类型:

String[] cars;

我们现在已经声明了一个包含字符串数组的变量。要向其中插入值,我们可以使用数组字面量 - 将值放在逗号分隔的列表中,在大括号内:

String[] cars = {"川川一号", "串串二号", "川川三号", "川川三号"};

要创建一个整数数组,你可以编写:

int[] myNum = {10, 20, 30, 40};
访问数组的元素

您可以通过引用索引号来访问数组元素。此语句访问汽车中第一个元素的值:

package test13;

public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] cars = {"川川一号", "川川二号", "川川三号", "川川三号"};
		System.out.println(cars[0]);
	}

}

运行: 在这里插入图片描述 如果你要访问第二个元素,那就是cars[1]

更改数组元素

要更改特定元素的值,直接对索引的值替换就行,举个例子你就知道了:

package test13;

public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] cars = {"川川一号", "川川二号", "川川三号", "川川三号"};
		cars[0] = "菜鸟";
		System.out.println(cars[0]);
	
	}

}

运行: 在这里插入图片描述

数组长度

要找出数组有多少个元素,请使用以下length函数:

package test13;

public class test2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] cars = {"川川一号", "川川二号", "川川三号", "川川三号"};
		System.out.println(cars.length);
	}

}

运行: 在这里插入图片描述

循环遍历数组

您可以使用循环遍历数组元素for,并使用该length 函数指定循环应运行的次数。

package test13;

public class test3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] cars = {"川川一号", "川川二号", "川川三号", "川川三号"};
		for (int i = 0; i             
关注
打赏
1665165634
查看更多评论
0.2228s