码迷,mamicode.com
首页 > 编程语言 > 详细

Java:数组

时间:2015-02-13 01:30:15      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

数组

数组容易出错的地方

  1. 注意角标越界问题:AarryIndexOutOfBoundsException
  2. 注意空指针异常:NullPointerException 当数组引用没有任何指向Null,而还在操作实体

数组例子

 

 1 class ArrayDemo 
 2 {
 3     public static void main(String[] args) 
 4     {
 5         //定义数组
 6 //        int[] arr1 = new int[5]{1,3,5,7,9};定义了数组长度和元素,但不推荐,容易出错(当数组长度和元素数量不等时)
 7         int[] arr1 = {1,3,5,7,9};
 8         int[] arr3 = new int[5];//定义已确定长度的数组
 9         arr3[0] = 2;
10         arr3[2] = 4;
11         arr3[3] = 6;
12         arr3[4] = 8;
13         
14         //通过循环遍历数组元素
15         System.out.println("******通过循环遍历元素");
16         for (int i=0; i<arr1.length ;i++ )
17         {
18             System.out.print("arr1[" + i + "]=" + arr1[i] + "\t");
19         }
20 
21         //通过定义方法遍历数组元素,并用逗号把元素隔开
22         printArray(arr3);
23     }
24     
25     public static void printArray(int[] arr)
26     {
27         System.out.println("******通过定义方法遍历数组元素");
28         System.out.print("[");
29             for (int i=0; i<arr.length ;i++ )
30             {
31                 if (i!=arr.length-1)
32                 {
33                     System.out.print(arr[i] + ",");
34                 }
35                 else
36                     System.out.println(arr[i] + "]");
37             }
38     }
39 }

 

Java:数组

标签:

原文地址:http://www.cnblogs.com/siyingcheng/p/4289480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!