java入门知识点4:数组

1.声明数组,分配空间
2.循环中的数组:score.length
3.使用 Arrays 类操作 Java 中的数组
4.使用 foreach 操作数组:遍历
5.二维数组

1.声明数组,分配空间
在这里插入图片描述
在这里插入图片描述
声明数组与分配空间结合:
在这里插入图片描述
即:

int[] score = {76, 83, 92, 87}
等价于int[] score = new int[]{76, 83, 92, 87}
score[0] = 76;

2.循环中的数组
注:数组名.length用于获取数组的长度

int[] score = {76, 83, 92, 87};
for(int i = 0; i < score.length; i++)
{
System.out.println("数组中第”+(i+1)+“个元素的值是:”+score);
}

3.使用 Arrays 类操作 Java 中的数组

1> 排序
语法: Arrays.sort(数组名);

import java.util.Arrays;

public class Demo01 {
	public static void main(String[] args) {
		int[] score = {78, 87, 98, 90, 76};
		Arrays.sort(score);
		System.out.println("排序后数组中元素的值");
		for(int i = 0; i < score.length; i++) {
			System.out.print(score[i]+" ");
		}
	}
}


运行结果:76 78 87 90 98

2> 将数组转换为字符串
语法: Arrays.toString(数组名);

import java.util.Arrays;

public class Demo01 {
	public static void main(String[] args) {
		int[] score = {78, 87, 98, 90, 76};
		System.out.println("排序后数组中元素的值:"+Arrays.toString(score));
	}
}


运行结果:排序后数组中元素的值:[78, 87, 98, 90, 76]

4.使用 foreach 操作数组
语法:
在这里插入图片描述
例:

public class HelloWorld {
    
  
	  public static void main(String[] args) {
        
						  int[] scores = { 89, 72, 64, 58, 93 };
        
			 	  	 	  Arrays.sort(scores);
        
				
                  for (int score : scores) {
			
	            System.out.println(score);
		
}	
}
}

运行结果:
58
64
72
89
93

5.二维数组

1>声明数组并分配空间:

 int[][] num = new int[2][3];
   等价于
   int[][] num;
   num = new int[2][3];

2>赋值:
num[0][0] = 12;
3>处理数组

public static void main(String[] args) {
        
			  
	String[][] names={
   
   {"tom","jack","mike"},{"zhangsan","lisi","wangwu"}};
                 
		for (int i = 0; i < names.length; i++) {
            
			
		for (int j = 0; j < names[i].length; j++) {
                
						System.out.println( names[i][j] );
			
}
            
			
	System.out.println();
		
}
	
}
运行结果:
tom
jack
mike

zhangsan
lisi
wangwu

猜你喜欢

转载自blog.csdn.net/qq_43501462/article/details/98514321
今日推荐