1 / 39

本章内容

本章内容. 2.1 数据类型 2.2 变量 2.3 运算符和表达式 2.4 字符串 2.5 输入与输出 2.6 数组 2.7 控制流程. 2.6 数组. 数组 :用来存储同一类型值的有序序列。 声明数组变量 : int[ ] a; // 或者 int a[ ] 注意 :此时还没为数组元素分配存储数据的空间. 数组初始化. 方法一:仅创建数组 int[ ] a = new int[100]; 注意: (1) 建议在声明一个变量时,立即初始化它。

kaveri
Download Presentation

本章内容

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 本章内容 • 2.1 数据类型 • 2.2 变量 • 2.3 运算符和表达式 • 2.4 字符串 • 2.5 输入与输出 • 2.6 数组 • 2.7 控制流程

  2. 2.6 数组 • 数组:用来存储同一类型值的有序序列。 • 声明数组变量: • int[ ] a; //或者int a[ ] 注意:此时还没为数组元素分配存储数据的空间

  3. 数组初始化 • 方法一:仅创建数组 • int[ ] a = new int[100]; 注意:(1) 建议在声明一个变量时,立即初始化它。 (2) 初始化数组时,数组的长度可以用一个已初始化的整型变量表示,如: int n=100; int[ ] a = new int [n]; • 方法二:创建数组并同时赋予初始值 • int[ ] a = {2, 3, 5, 7}; • 方法三:利用匿名数组: int smallPrimes = new int[ ] {2, 3, 5}; //等号右边是一个匿名数组 使用这种语法形式可以在不创建新变量的情况下重新初始化一个数组。 smallPrimes = new int[ ] {2, 3, 5, 7, 11, 13}; 等价于下列语句的简写形式: int[ ] anonymous = {2, 3, 5, 7, 11, 13}; smallPrimes = anonymous;

  4. 数组赋值 • (3) 为数组元素赋值: int [ ] a= new int[4]; a[0] =0; a[1]=1; a[2]=2; a[3]=3; 注意:数组下标从0开始

  5. 数组的遍历 “for each”循环 • JDK 5.0增加了一种很有趣的循环结构语法,可以用来依次处理数组(或其它类型的元素集合)中的每个元素: for(类型variable: collection) statement • 定义了一个variable,用于暂存集合中的每一个元素。 注意: variable的定义不能在for语句之外, collection只能是一维数组

  6. For each循环语句示例 public class ForEachTest1 { public static void main(String[] args) { int[] intarray = {0,1,2,3,4,5}; for(int element:intarray) System.out.println(element); } } • 运行结果: 是打印数组intarray中的每一个元素。

  7. 数组的长度和边界 • 在Java语言中,数组下标从0开始,到数组长度减1结束。 • 任何数组都有公有变量length。它是只读变量,只可检测,不可赋值,因为数组一旦分配内存后,其长度就不再变化。 • 为了安全考虑,数组的存取在程序运行时实时检查,企图使用小于零或大于数组长度的下标都会引起越界异常(ArrayIndexOutofBoundException)(异常处理我们将在后面的章节中给出)。

  8. For each 语句示例2 import java.util.*; public class ForEachTest2 { public static void main(String[] args) { int[] intarray = {0,1,2,3,4,5}; System.out.print("array:= "); for(int element:intarray) System.out.print(element+"\t"); System.out.println("\n The length of the array is:"+intarray.length); System.out.println("Input the index of the array number:"); Scanner in=new Scanner(System.in); int num=in.nextInt(); System.out.println("array["+num+"]= "+intarray[num]); } }

  9. 多维数组 • 多维数组适用于表示表格或更复杂的排列形式。 • 多维数组声明: • double[ ] [ ] balances; • 数组初始化(两种方式): • balances = new double[10][10]; balances = new double[m][n]; • int[ ] [ ] magicSquare = { {16, 3, 2, 13}, {5, 10, 11, 8}, {9, 6, 7, 12}, {4, 15, 14, 1} }//注意书写格式 • int[ ] [ ] magicSquare = new int[ ] [ ] • { • {16, 3, 2, 13}, • {5, 10, 11, 8}, • {9, 6, 7, 12}, • {4, 15, 14, 1}, • } 演示MagicSquare.java

  10. 多维数组示例 public class MagicSquare { public static void main(String[] args) { int i=0; int[ ][ ] magicsquare= {{16,3,2,13},{5, 10, 11, 8},{9, 6, 7, 12},{4, 15, 14, 1}}; for(int[] row: magicsquare) for(int element: row) { System.out.print(element+"\t"); i++; if (i%4==0) System.out.print("\n"); } } }

  11. 不规则数组 • Java实际上没有多维数组,只有一维数组。多维数组被解释为“数组的数组”。 • 不规则数组:即数组的每一行都有不同的长度。例如: 1 1 1 1 2 1 1 3 3 1 • 应当这样声明此不规则数组: • int[ ] [ ] adds = new int[4] [ ]; • for(int n = 0; n <= 4; n++) • odds[n] = new int[n+ 1];

  12. array[0][0] array[0][1] … array[0][n] array[1][0] array[1][1] … array[1][m] array[2][0] array[2][1] … array[2][k] Java中的数组存储方式 • C/C++种要求二维数组中每一维长度必须一致。 • 在Java中,多维数组的每一维长度可以不同。例如, int array [3][ ]=new int[3][ ]; • array对应的二维表如下表所示,有可能n ≠ m ≠ k 。

  13. 数组的行交换操作 • 如果定义一个二维数组: • int balance[10][6] = {……}; • 则该数组实际上是一个包含了10个元素的数组;而每个元素又是一个有6个整数组成的数组。 • 表达式: balance[i]表示第i个子数组,而就是二维表的第i行,它本身也是一个数组, balance[i][j]引用这个数组的第j项。 • 下面的代码可以将balance第i行和第i + 1行交换: • double[] temp = balances[i]; • balances[i] = balances[i + 1]; • balances[i + 1] = temp;

  14. 多维数组示例程序 public class ArrayTest { public static void main(String[] args) { int[ ][ ] intarray = new int[4][ ]; intarray[0] =new int[ ] {1}; intarray[1] =new int[ ] {0,1}; intarray[2] =new int[ ] {0,1,2}; intarray[3] =new int[ ] {0,1,2,3}; for( int[ ] array:intarray ) { System.out.print("\n"); for( int element: array ) System.out.print(element+"\t"); } } }

  15. 不规则数组的访问 • 可以这样访问不规则数组: • for(int n = 0; n < odds.length; n++) • for(int k = 0; k <odds[n].length; k++) //第二维 • { • ……//compute lotteryOdds; • odds[n][k] = lotteryOdds; • } • 使用length属性能方便地控制循环边界。 #

  16. 大数值的表示 • 若基本的整数和浮点数不能满足需求所表示的大数值,就可以使用java.math包中的两个类: • BigInteger • BigDecimal • 注意: (1) 不需要用new初始化 (2) 赋值语句使用valueOf()方法。例如: BigInteger bint = BigInteger.valueOf(1000); BigDecimal bdec= BigDecimal.valueOf(1000.0); (3) 不能使用普通的算术运算符处理大数值。在这些类中,普通的算术运算通过专门的方法来运算,例如: • …… • BigInteger c = a.add(b); // c = a + b • BigInteger d = c.multiply(b); // d = c * b • …… #

  17. 本章内容 • 2.1 数据类型 • 2.2 变量 • 2.3 运算符和表达式 • 2.4 字符串 • 2.5 输入与输出 • 2.6 数组 • 2.7 控制流程

  18. 控制语句 • Java程序通过控制语句来执行程序流,完成一定的任务。 • Java中的控制语句有以下几类: ◇ 分支语句:if - else, switch ◇ 循环语句:while, do-while, for ◇ 跳转语句:break, continue, return ◇ 异常处理语句:try – catch - finally, throw ◇ 注释语句://,/* */, /** */

  19. 块作用域 块(block) • 即复合语句,指有一对{ }括起来的若干条简单的Java语句。 • 块确定了变量的作用域;块还可以嵌套。 例如: • public static void main(String[ ] args) { • int n; • …… • { • int k; • …… • }// k is only defined up to here • k=10 ; //Error • }

  20. 块作用域(续) • 不能在嵌套的两个块中声明多个同名变量。例如下面代码将不能通过编译: public static void main(String[ ] args) { int n; …… { int k; int n; …… }// k is only defined up to here } • 注意与C++的区别:在C++中可以在嵌套的块中重定义一个变量。在内层定义的变量会覆盖在外层定义的变量。但Java不允许这样使用。

  21. 分支语句 • 分支语句提供了一种控制机制,使得程序运行过程中某种条件得到满足时,转去执行与之对应的特定语句。 • 1.条件语句 if-elseif(boolean-expression)statement1;[ else statement2; ]

  22. if-else语句演示 import java.util.*; class ifelseTest { public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.println("Input Your sales:"); double yourSales=in.nextDouble(); System.out.println("Input Your target:"); double target=in.nextDouble(); if (yourSales>=target){ double bonus=100.0; System.out.println("Your performance is good and you bonus is "+bonus); }else System.out.println("You are fired"); } } 演示ifelseTest.java

  23. 多分支语句 2.多分支语句 switchswitch (expression){case value1 : statement1;break;case value2 : statement2;break;…………case valueN : statemendN;break;[default : defaultStatement; ] //可选 } • break语句用来在执行完某个case分支后,使程序跳出switch语句,即终止switch语句的执行。 • 如果将default语句放在了第一行,则不管expression与case中的value是否匹配,程序会从default开始执行直到第一个break出现。 • case标签后的value值必须是byte, short, int, char或枚举常量(第4章),不能是字符串,long,float 或double型。

  24. switch语句演示 import java.util.*; class switchTest { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("Please input an option : 1,2,3 "); int op =in.nextInt(); switch (op) { case 1: System.out.println(" Your option is 1"); break; case 2: System.out.println(" Your option is 2 "); break; case 3: System.out.println(" Your option is 3"); break; default: System.out.println(" Your option is not in the list "); } } } 将break语句删除,程序运行结果会有什么变化? 演示switchTest.java

  25. switch语句的流程图 • 注意:在一些特殊情况下,可以使多个不同的case值执行一组相同的操作,这时在相关的case之间可以不用break。

  26. 循环语句 1.while语句[initialization]while (condition){body;[iteration;]} 2.do-while语句[initialization]do {body;[iteration;]} while (condition); 3.for语句for (initialization; condition; iteration){body;}

  27. 循环语句的流程图 do-while语句 while语句 for语句

  28. 循环的条件检测 • 在循环中,检查两个浮点数是否相等需要特别小心。例如: • for(double x = 0.0; x != 10; x += 0.1) • …… • 该循环可能永远都不会结束,为什么??? • 原因在于:由于舍入的误差,最终可能永远达不到精确值。上述循环中,0.1无法精确地用二进制表示,所以x将无法达到精确值10. 演示ForTest.java

  29. 跳转语句 • 常用的跳转语句包含: 1. break语句 2. continue语句 3. return语句

  30. 跳转语句——break 1.break语句 • switch语句中,break语句用来终止switch语句的执行。 • 在Java中,可以为每个代码块加一个括号,一个代码块通常是用大括号{}括起来的一段代码。例如 while(years <= 100) { …… if(balance >= goal) break; …… } years ++; //break语句被执行之后,跳到此语句执行 …… • break语句使得程序流程跳出它所在的块,并从紧跟该块之后的第一条语句处执行。

  31. 带标签的break语句 • 在嵌套很深的循环语句中会发生一些很难预料的事情,此时可能更加希望完全跳出所有循环语句。 • Java提供带标签的break语句实现该功能。

  32. 带标签的break语句(续) • 带标签的break语句中,标签必须放置在要跳出的循环(或语句块)之前,而且必须紧跟一个冒号: read_data: //标签 while (. . .) { // while语句被read_data标签作标记 . . . for (. . .) { // for语句是内层循环,不要用标签标记 System.out.print("Enter a number >= 0: "); if (….) // should never happen—can't go on breakread_data; // 跳出 read_data 所标记的循环 . . . } } if (n < 0) { …… } else { …… } //在“breakread_data;” 语句被执行之后,控制跳到本语句

  33. 带标签的break语句示例 import java.util.*; public class LabelBreakTest { public static void main(String[] args) { int i=0,j=0,num=0,temp; int[] sum = new int[]{0,0}; boolean done=false; Scanner in = new Scanner(System.in); read_data: while(!done){ temp=0; System.out.println("please input four positive number: "); for(i=0;i<4;i++){ num = in.nextInt(); if (num<0) break read_data; temp+=num; } sum[j]=temp; if (++j==2) done=true; } if (num<0) System.out.println("Input error!" +"("+num+")"); else System.out.println("Bigger Sum is: sum["+ (i=sum[0]>sum[1]? 0:1)+"]="+sum[i]); } } //功能:输入两组正整数,每组四个,并输出四个数之和较大的一组的和,如果输入不符合要求,则中断输入,打印输入出错信息。

  34. 跳转语句——continue 2.continue语句 • continue语句用来结束本次循环,并将控制转移到最内层循环的首部。 例如: • 如果continue语句被执行,则立即跳过……部分,执行for循环的首部。 for( int i= 0; i <10; i++ ){ if( i == 5 ) { continue; } …… }

  35. continue语句示例 import java.util.*; public class ContinueTest { public static void main(String[] args) { int i=0,j=0,num=0,temp; int[] sum = new int[]{0,0}; Scanner in = new Scanner(System.in); while(j<2){ temp=0; System.out.println("please input four numbers: "); for(i=0;i<4;i++){ num = in.nextInt(); if (num<0) continue; temp+=num; } sum[j]=temp; j++; } System.out.println("Bigger Sum is: sum["+ (i=sum[0]>sum[1]? 0:1)+"]="+sum[i]); } } //功能:输入两组整数,每组四个,并输出所输入的四个数中正数之和较大的一组的和。

  36. 带标签的continue语句 • 也可以用带标签的continue语句跳转到括号指明的外层循环中,这时的格式为 • continue outerLable; 例如: outer: for( int i=0; i<10; i++ ) { //外层循环 inner: for( int j=0; j<10; j++ ) { //内层循环 if( i<j ) { …… continue outer; } …… } //内层循环结束 …… } //外层循环结束

  37. 带标签的continue语句示例 import java.util.*; public class LabelContinueTest { public static void main(String[] args) { int i=0,j=0,num=0,temp; int[] sum = new int[]{0,0}; boolean done=false; Scanner in = new Scanner(System.in); outer: while(!done){ temp=0; System.out.println("please input four positive number: "); inner: for(i=0;i<4;i++){ num = in.nextInt(); if (num<0) continue outer; temp+=num; } sum[j]=temp; if (++j==2) done=true; } System.out.println("Bigger Sum is: sum["+ (i=sum[0]>sum[1]? 0:1)+"]="+sum[i]); } } //功能:输入两组正整数,每组四个,并输出四个数之和较大的一组的和,如果输入不符合要求,则继续输入,直到两组输入的数都为正整数。

  38. 跳转语句——return 程序转移相关语句 return • return语句从当前方法中退出,返回到调用该方法的语句处,并从紧跟该语句的下一条语句继续程序的执行。返回语句有两种格式: • return expression; //方法需要返回某种类型数据时 • return; //当方法的返回类型为void时 • 注意:return语句通常用在一个方法体的最后;否则会产生编译错误——除非用在if-else语句中。

  39. 思考: 1. Java中的标识符是由哪些字符组成的? 2. Java中有哪些保留字?简单数据类型包含哪几种?各种数据类型变量的定义方法和常量的表示方法及取值范围。 3. Java 中各简单数据类型间的优先次序和自动转换规则是什么?   各数据类型间在什么情况下,进行自动转换,在什么情况下使用强制转换? 4. Java中有哪些运算符?这些运算符的优先关系是怎样的? 5. Java 中有哪些控制语句?你了解每一种控制语句的语法规则吗? 6. Java 中的一维数组和多维数组在数组动态初始化和静态初始化时有何不同? 7. Java中的字符串有两种表示方法,这两种表示方法有什么不同? 8. 如何访问字符串?如何修改字符串?如何对两个字符串进行比较?

More Related