方法与数组

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 1 /**
 2     数组的定义:一组能够存储相同数据类型的数据集合。
 3     数组一定要有长度
 4     数组中的每个数据称为元素,
 5     数组元素的位置从0开始
 6     数组中的位置称为下标
 7     
 8 */
 9 import java.util.Scanner;
10 public class Test6{
11     public static void main(String[] args){
12         
13         //第一种,
14         int[] nums = new int[5];
15         /*
16         nums[0] = 1;
17         nums[1] = 2;
18         nums[2] = 3;
19         nums[3] = 4;
20         nums[4] = 5;
21         */
22         for(int i=0;i<nums.length;i++){
23             nums[i] = i+1;
24         }
25         
26         //第二种
27         int[] nums2; //先声明(定义)
28         nums2 = new int[5];
29         
30         //第三种:
31         int[] nums3 = new int[]{1,2,3,4,5};
32         
33         //第四种:
34         int[] nums4 = {1,2,3,4,5};
35         //所有的数组都有一个属性是:length
36         System.out.println("数组的长度是:"+nums4.length);
37     }
38 }
View Code

 

 

 

 

 1 /**
 2     数组的遍历
 3     
 4 */
 5 import java.util.Scanner;
 6 public class Test7{
 7     public static void main(String[] args){
 8         
 9         int[] scores = {59,75,83,93,100};
10         System.out.println("数组的长度:"+scores.length);
11         
12         //for遍历
13         int len = scores.length;
14         for(int i=0;i<len;i++){
15             
16             int score = scores[i];
17             System.out.println(score);
18         }
19         System.out.println(scores);
20         
21         System.out.println("-----------------");
22         //forearch JDK1.5之后新增的特性
23         for(int x:scores){
24             System.out.println(x);
25         }
26         System.out.println("--------------");
27         //调用方法
28         //print(scores);
29         //print2(59,75,83,93,100);
30         
31         //print3(null);
32         
33         print4(scores);
34         
35         
36         //new关键字表示创建一个数组,
37         int[] nums = new int[]{1,2,3,4,5};
38         
39     }
40     
41     public static void print(int[] x){
42         int len = x.length;
43         for(int i=0;i<len;i++){
44             
45             System.out.println(x[i]);
46         }
47     }
48     
49     //JDK1.5可变参数
50     //可变参数只能是参数列表中的最后一个
51     //可变参数作为数组使用
52     public static void print2(int k,int... x){
53         int len = x.length;
54         for(int i=0;i<len;i++){
55             
56             System.out.println(x[i]);
57         }
58     }
59     
60     //测试数组的异常NullPointerException(空指针)
61     public static void print3(int[] x){
62         // java.lang.NullPointerException
63         //当一个变量为null(没有赋值时)时,我们去调用了该变量的属性和方法
64         System.out.println("数组的长度为:"+x.length);
65     }
66     //测试数组的异常,数组下标越界
67     // java.lang.ArrayIndexOutOfBoundsException
68     public static void print4(int[] x){
69         for(int i=0;i<=x.length;i++){
70             System.out.println(x[i]);
71         }
72     }
73 }

 

posted @ 2021-12-06 08:24  juham  阅读(28)  评论(0编辑  收藏  举报