Java 入门 之 数组与循环
2016-01-17 15:16
423 查看
本节,主要掌握的知识点是数组的初始化(两种常见的方式)以及 Try/Catch Block 的应用 。
数组的定义非常简单,不废话,直接上代码:
提到数组,肯定就离不开数组越界异常,越界异常常见的处理方式还是 Try/Catch Block
具体实现,见代码如下:
myvec the length is: 3
2 3 4 5 6
7 8 9 10 11
12 13 14 15 16
17 18 19 20 21
数组越界!!!
注:
由于输出超过了 20 ,数组只申请了20个整形空间,从而无法实现赋值操作,抛出异常,得到输出,数组越界。
数组的定义非常简单,不废话,直接上代码:
package Arr_Pack; public class Arr_Class { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int []myarr = new int[20]; int []myvec = {1,2,3}; System.out.println("myvec the length is: " + myvec.length); for (int loop_t = 0;loop_t<myarr.length;loop_t++) { myarr[loop_t] = loop_t+2; if(loop_t%5 == 0 && loop_t != 0) System.out.println(); System.out.print(myarr[loop_t]+"\t"); } } }
提到数组,肯定就离不开数组越界异常,越界异常常见的处理方式还是 Try/Catch Block
具体实现,见代码如下:
package Arr_Pack; public class Arr_Class { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int []myarr = new int[20]; int []myvec = {1,2,3}; System.out.println("myvec the length is: " + myvec.length); try{ for (int loop_t = 0;loop_t<21;loop_t++) { myarr[loop_t] = loop_t+2; if(loop_t%5 == 0 && loop_t != 0) System.out.println(); System.out.print(myarr[loop_t]+"\t"); } } catch(Exception e) { System.out.println(); System.out.println("数组越界!!!"); } } }该代码段输出如下:
myvec the length is: 3
2 3 4 5 6
7 8 9 10 11
12 13 14 15 16
17 18 19 20 21
数组越界!!!
注:
由于输出超过了 20 ,数组只申请了20个整形空间,从而无法实现赋值操作,抛出异常,得到输出,数组越界。
相关文章推荐
- ruby 数组使用教程
- Ruby中的数组和散列表的使用详解
- C#实现AddRange为数组添加多个元素的方法
- C#比较二个数组并找出相同或不同元素的方法
- C#中循环语句:while、for、foreach的使用
- C#动态调整数组大小的方法
- Lua中数字for循环实例
- 详解Lua中的数组概念知识
- Perl中的列表和数组学习笔记
- Sql存储过程游标循环的用法及sql如何使用cursor写一个简单的循环
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
- Shell中的for和while循环详细总结
- C#中数组初始化与数组元素复制的方法
- C#交错数组用法实例
- Linux Shell 数组建立及使用技巧
- PowerShell数组的一些操作技巧
- C#通过yield实现数组全排列的方法
- C#不重复输出一个数组中所有元素的方法
- C#实现将数组内元素打乱顺序的方法
- Ruby简明教程之数组和Hash介绍