资源描述
,单击此处编辑母版文本样式,第二级,第三级,第四级,第五级,单击此处编辑母版标题样式,JAVA,语言程序设计,*,第,*,页,第三章 类的方法,JAVA,语言程序设计,1,目录,3.1 方法的控制流程,3.2 异常处理简介,3.3 方法的重载,(overloading),3.4,本章小结,2,3.1 方法的控制流程,方法的控制流程,Java,程序通过控制语句来控制方法的执行流程,Java,中的流程控制结构主要有三种,顺序结构,选择结构,if,语句(二路选择结构),switch,语句(多路选择结构),循环结构,for,语句,while,语句,do-while,语句,3,3.1.1,if,选择结构,语法形式,只有,if,分支,没有,else,分支,if(boolean-expression),/statement1;,if-else,语句,if(boolean-expression),/statement1;,else,/statement2;,方法的控制流程,4,3.1.1,if,选择结构(续),if-else,语句的特殊形式,if,(boolean expression),/statement1;,else if,(boolean expression),/statement2;,else if,(boolean expression),/statement;,else,/statement;,方法的控制流程,5,ex3_1,输入一个年份,判断它是不是闰年。,闰年,:,能被,4,整除但不能被,100,整除,或者能被,400,整除。,import java.io.*;,public class ex3_1,public static void main(String args)throws IOException,int year;,boolean IsLeapYear;,System.out.println(Enter the year:);,/,输入一个年份;,BufferedReader in=new BufferedReader(,new InputStreamReader(System.in);,year=(new Integer(in.readLine().intValue();,3.1.1,if,选择结构(续),ex3_1.java,方法的控制流程,6,IsLeapYear=(year%4=0&year%100!=0),|,(year%400=0);,if(IsLeapYear),System.out.print(year);,System.out.println(is a leap year);,else,System.out.print(year);,System.out.println(is not a leap year);,3.1.1,if,选择结构(续),方法的控制流程,另一种实现:,7,输入两个整数比较大小,import java.io.*;,public class ex3_2,public static void main(String args)throws IOException,int x,y;,BufferedReader in=new BufferedReader(,new InputStreamReader(System.in);,System.out.println(Enter x and y:);,x=(new Integer(in.readLine().intValue();,y=(new Integer(in.readLine().intValue();,if(x!=y),if(xy)System.out.println(xy);,else System.out.println(x=90)grade=A;,else if(testscore=80)grade=B;,else if(testscore=70)grade=C;,else if(testscore=60)grade=D;,else grade=F;,System.out.println(Grade=+grade);,程序输出:,Grade=C,3.1.1,if,选择结构(续),方法的控制流程,9,3.1.2,switch,选择结构,switch,语句是多分支的选择结构,switch(switch-expression),case value1:statements for case1;break;,case value2:statements for case2;break;,.,case valueN:statements for caseN;break;,default:statements for default case;break;,注意问题,switch-expression、,常量值,value1,到,valueN,必须是整形或字符型,如果表达式的值和某个,case,后面的值相同,则从该,case,之后开始执行,直到,break,语句为止,default,是可有可无的,若没有一个常量与表达式的值相同,则从,default,之后开始执行,方法的控制流程,10,if,(i=,1,),statementA();,else if,(i=,2,),statementB();,else if,(i=,3,)|(i=,4,),statementC();,else if,(i=,5,),statementD();,else,statementF();,switch,(i),case,1,:,statementA();break;,case,2,:,statementB();break;,case,3,:,case,4,:,statementC();break;,case,5,:,statementD();break;,default,:statementF();,3.1.2,switch,选择结构(续),用,switch,代替,if,方法的控制流程,11,使用,switch,结构计算每个月的天数,static int daysInMonth(int month),int days;,switch(month),case 2:days=28;break;,case 4:,case 6:,case 9:,case 11:days=30;break;,default:days=31;,return(days);,3.1.2,switch,选择结构(续),例3_2,方法的控制流程,多个,case,语句合并,12,public static void main(String args)System.out.println(gradeLevel(100)=+gradeLevel(100);System.out.println(gradeLevel(95.5)=+gradeLevel(95.5);,3.1.2,switch,选择结构(续),例3_3,方法的控制流程,14,Switch,语句:小心,case,穿透,public class TestSwitch,public static void main(String args),char c=a;,switch(c),case a:System.,out,.println(a);,case b:System.,out,.println(b);,case c:System.,out,.println(c);,输出:,a,b,c,15,for,循环结构,是,Java,三个循环语句中功能较强、使用较广泛的一个,for,循环可以嵌套,一般语法格式如下,for(,start-expression,;,check-expression,;,update-expression,),/body of the loop;,解释,start-expression,完成循环变量和其他变量的初始化工作,check-expression,是返回布尔值的条件表达式,用于判断循环是否继续,update-expression,用来修整循环变量,改变循环条件,三个表达式之间用分号隔开,3.1.3,for,循环结构,方法的控制流程,16,for,语句的执行过程,首先根据初始表达式,start-expression,,完成必要的初始化工作;再判断表达式,check-expression,的值,若为真,则执行循环体,执行完循环体后再返回表达式,update-expression,,计算并修改循环条件,这样一轮循环就结束了,第二轮循环从计算并判断表达式,check-expression,开始,若表达式的值仍为真,则循环继续,否则跳出整个,for,语句执行,for,循环下面的句子,3.1.3,for,循环结构(续),方法的控制流程,17,打印九九乘数表,public class MultiTable,public static void main(String args),for(int i=1;i=9;i+),for(int j=1;j=i;j+),System.out.print(+i+*+j+=+i*j);,System.out.println();,3.1.3,for,循环结构(续),方法的控制流程,18,输入一个整数,输出它所有的因数,import java.io.*;,public class ex3_7,public static void main(String args)throws IOException,int n,k;,BufferedReader in=new BufferedReader(,new InputStreamReader(System.in);,System.out.println(Enter a positive integer:);,n=(new Integer(in.readLine().intValue();,System.out.print(Number +n+Factors );,for(k=1;k=n;k+),if(n%k=0)System.out.print(k+);,System.out.println();,3.1.3,for,循环结构(续),补充,ex3_7.java(lue),方法的控制流程,19,逗号运算符,可用在,for,循环控制表达式的初始化和递增两部分。在这两部分中可以存在多个由逗号分隔的语句,这些语句会被依次计算,public class ex3_8,public static void main(String args),for(int i=1,j=i+10;i 5;i+,j=i*2),System.out.println(i=+i+j=+j);,3.1.3,for,循环结构(续),逗号运算符,方法的控制流程,20,while,语句,实现“当型”循环,其一般语法格式如下:,while(check-expression),/body of the loop;,解释,条件表达式(,check-expression),的返回值为布尔型,循环体可以是单个语句,也可以是复合语句块,执行过程,先判断,check-expression,的值,为真则执行循环体,循环体执行完后再无条件转向条件表达式做计算与判断;当计算出条件表达式的值为假时,跳过循环体执行,while,语句后面的语句。若为真,则继续执行循环,3.1.4,while,循环结构,方法的控制流程,21,循环接受并输出从键盘输入的字符,直到输入的字符为*为止,(*),public class charin,public static void main(String args)throws Exception,char ch=a;,while(ch!=*),System.out.println(ch);,ch=(char)System.in.read();/,接收键盘输入,3.1.4,while,循环结构(续),方法的控制流程,22,计算数列,1,2,10,的和。,public class ex3_4,public static void main(String args),int i=1,sum=0;,while(i=10),sum+=i;,i+;,System.out.println(sum=+sum);,3.1.4,while,循环结构(续),补充,ex3_4.java(lue),方法的控制流程,23,do-while,语句,实现“直到型”循环,一般语法结构如下,do,/body of the loop;,while(check-expression);,其使用与,while,语句很类似,不同的是它首先无条件的执行一遍循环体,再来判断条件表达式的值,若表达式的值为真,则再运行循环体,否则跳出,do-while,循环,执行下面的语句,特点:它的循环体至少要执行一次,3.1.5,do-while,循环结构,方法的控制流程,24,/,while(i=10),sum+=i;,i+;,(sum=+sum);,/,do ,sum+=i;,i+;,while(i=10);,(sum=+sum);,比较这两段程序,3.1.5,do-while,循环结构(续),方法的控制流程,25,功能,跳出循环,不再执行剩余部分,适用场合,在,switch,结构中,用来终止,switch,语句的执行,在,for,循环及,while,循环结构中,用于终止,break,语句所在的最内层循环;,也可用在代码块中,用于跳出它所指定的块,3.1.6,break,语句,方法的控制流程,26,简单,break,应用举例,public class BreakTest,public static void main(String args),String output=;,int i;,for(i=1;i=10;i+),if(i=5),break;/break loop only if count=5,/continue,的不同,output+=i+;,output+=nBroke out of loop at i=+i;,System.out.println(output);,方法的控制流程,3.1.6,break,语句(续),例3_,5,27,解释,执行,break,语句时,程序流程跳出,for,循环,3.1.6,break,语句(续),例3_,5,运行结果,方法的控制流程,28,在嵌套循环中使用,break,语句:使用下面的程序来实现例3-4的九九乘法表,public class Examp3_6,public static void main(String args),for(int i=1;i=9;i+),for(int j=1;j i)break;,System.out.print(+i+*+j+=+i*j);,System.out.println();,3.1.6,break,语句(续),例3_,6(lue),方法的控制流程,29,continue,语句,必须用于循环结构中,停止本次迭代,回到循环起始处,开始下一次迭代过程,有两种使用格式,不带标号的,continue,语句,终止当前这一轮的循环,跳出本轮循环剩余的语句,直接进入当前循环的下一轮,带标号的,continue,语句,使程序的流程直接转入标号标明的循环层次,3.1.7,continue,语句,方法的控制流程,30,public class Examp3_6,getString().,BufferedReader in=new BufferedReader(,/statement2;,return 0;,MethodOverloading m=new MethodOverloading();,也可用在代码块中,用于跳出它所指定的块,case c:System.,if(IsLeapYear),BufferedReader in=new BufferedReader(,该异常是系统定义好的类,对应系统可识别的错误,所以Java虚拟会自动中止程序的执行流程,并新建一个该异常类的对象,即抛出数组越界异常,错误的类型:编译错误、运行错误、逻辑错误,println(greetingsi);,不带标号的,continue,语句,在,while,或,do-while,循环中,会使流程直接跳转至条件表达式,在,for,循环中,会使流程跳转至表达式,update-expression,,计算并修改循环变量后再判断循环条件,3.1.7,continue,语句(续),不带标号的,continue,语句,方法的控制流程,31,简单的,continue,语句举例,public class ContinueTest,public static void main(String args),String output=;,int i;,for(i=1;i=10;i+),if(i=5)continue;/skip remaining code in this loop,output+=i+;,output+=nUsing continue to skip printing 5;,output+=ni=+i;,System.out.println(output);,3.1.7,continue,语句(续),例3_,8,方法的控制流程,32,运行结果,1 2 3 4 6 7 8 9 10,Using continue to skip printing 5,i=11,说明,continue,语句并没有跳出循环体,而是跳过本次循环,进入下一轮循环,3.1.7,continue,语句(续),例3_,8,运行结果,方法的控制流程,33,打印2到9之间的偶数的平方,但是不包括偶数6的平方,public class Examp3_9,public static void main(String args),for(int i=2;i=9;i+=2),if(i=6),continue;,System.out.println(i*i);,3.1.7,continue,语句(续),例3_,9(lue),方法的控制流程,34,错误的类型,:,编译错误、运行错误、逻辑错误,Java,异常是,Java,提供的用于处理程序中错误的一种机制。,所谓错误,是在程序运行过程中发生的异常事件,比如除,0,溢出、数组越界、文件找不到等。,设计良好的程序应该在异常发生时提供处理这些错误的方法,使得程序不会因异常发生而阻断或产生不可预见的结果。,3.2 异常处理简介,35,3.2.1 异常处理,Java,程序的执行过程中如出现异常事件,可生成一个异常类对象,该异常类对象封装了异常事件的信息,并将被提交给,java,运行时系统,这个过程被称为抛出(,throw,)异常。,当,java,运行时系统接收到异常对象时,会寻找能处理该异常的代码并把当前异常对象交给其处理,该过程称为捕获(,catch,)异常。,异常处理简介,36,3.2.1,异常处理,37,3.2.2 错误的概念(续),异常和错误类的层次结构,异常处理简介,J2SDK,定义了很多异常类,对应了各种可能出现的异常事件。,38,3.2.2 错误的概念,错误,由硬件系统或,JVM,导致的故障,致命性的,用户程序无法处理,Error,类是所有错误类的父类,异常,是程序运行错误,非致命性的,可编制程序捕获和处理,Exception,类是所有异常类的父类,异常处理简介,39,Java,预定义的一些常见异常,ArithmeticException,整数除法中除数为0,NullPointerException,访问的对象还没有实例化,NegativeArraySizeException,创建数组时元素个数是负数,ArrayIndexOutOfBoundsException,访问数组元素时,数组下标越界,ArrayStoreException,程序试图向数组中存取错误类型的数据,FileNotFoundException,试图存取一个并不存在的文件,IOException,通常的,I/O,错误,3.2.2 错误的概念(续),预定义的一些常见异常,异常处理简介,RuntimeException,非,RuntimeException,40,测试系统定义的运行异常数组越界出现的异常,(,加入异常,),import java.io.*;,public class HelloWorld,public static void main(String args),int i=0;,String greetings =Hello world!,No,I mean it!,HELLO WORLD!;,while(i 4),System.out.println(greetingsi);,i+;,3.2.2 错误的概念(续),例3_1,1,异常处理简介,41,运行结果,Hello world!,No,I mean it!,HELLO WORLD!,at HelloWorld.main(HelloWorld.java:7),说明,访问数组下标越界,导致,ArrayIndexOutOfBoundsException,异常,该异常是系统定义好的类,对应系统可识别的错误,所以,Java,虚拟会自动中止程序的执行流程,并新建一个该异常类的对象,即抛出数组越界异常,3.2.2 错误的概念(续),例3_1,1,运行结果,异常处理简介,42,3.2.3 异常的处理,对于检查型,(,非,RuntimeException,子类的,),异常,,Java,强迫程序必须进行处理。处理方法有两种:,声明抛出异常,不在当前方法内处理异常,而是把异常抛出到调用方法中。使用,throws,关键字声明,捕获异常,使用,trycatch(),块,捕获到所发生的异常,并进行相应的处理,异常处理简介,43,声明抛出异常,如果不想在当前方法内处理异常,可使用,throws,声明将异常抛出到调用方法中。,如果所有的方法都选择了抛出此异常,最后,JVM,将捕获它,输出相关错误信息,并终止程序运行。,在异常被抛出过程中,任何方法都可捕获它并进行相应的处理。,3.2.3 异常的处理(续),声明抛出异常,异常处理简介,44,45,语法格式,try,statement(s),catch(exceptiontype name),statement(s),finally,statement(s),3.2.3 异常的处理(续),捕获异常,异常处理简介,46,说明,try,语句:,包含可能产生异常的代码块,catch,语句,异常处理语句,通常用到两个方法,getMessage(),返回一个字符串对发生的异常进行描述。,printStackTrace(),给出方法调用序列,一直到异常产生位置,finally,语句,无论是否发生异常,都进行处理。,注意事项,多个异常需要捕获时,异常类型的顺序很重要。,3.2.3 异常的处理(续),捕获异常,异常处理简介,47,读入两个整数,第一个数除以第二个数,之后输出,import java.io.*;,public class ExceptionTester,public static void main(String args),System.out.println(Enter the first number:);,int number1=Keyboard.getInteger();,System.out.println(Enter the second number:);,int number2=Keyboard.getInteger();,System.out.print(number1+/+number2+=);,int result=number1/number2;,System.out.println(result);,3.2.3 异常的处理(续),例3_1,2,异常处理简介,48,其中,,Keyboard,类的声明如下,import java.io.*;,public class Keyboard,static BufferedReader inputStream=new BufferedReader,(new InputStreamReader(System.in);,public static int getInteger(),try,return(Integer.valueOf(inputStream.readLine().trim().intValue();,catch(Exception e),e.printStackTrace();,return 0;,public static String getString(),try,return(inputStream.readLine();,catch(IOException e),return 0;,3.2.3 异常的处理(续),例3_1,2,异常处理简介,49,捕获,NumberFormatException,类型的异常,import java.io.*;,public class ExceptionTester2 ,public static void main(String args),int number1=0,number2=0;,try,System.out.println(Enter the first number:);,number1=Integer.valueOf(Keyboard.getString().intValue();,System.out.println(Enter the second number:);,number2=Integer.valueOf(Keyboard.getString().intValue();,catch(NumberFormatException e),System.out.println(Those were not proper integers!I quit!);,System.exit(-1);,System.out.print(number1+/+number2+=);,int result=number1/number2;,System.out.println(result);,异常处理简介,3.2.3 异常的处理(续),例3_1,3,51,运行结果,Enter the first number:,abc,Those were not proper integers!I quit!,异常处理简介,3.2.3 异常的处理(续),例3_1,3,运行结果,52,捕获被零除的异常(,ArithmeticException,类型的异常),try,System.out.println(Enter the first number:);,number1=Integer.valueOf(Keyboard.getString().intValue();,System.out.println(Enter the second number:);,number2=Integer.valueOf(Keyboard.getString().intValue();,result=number1/number2;,catch(NumberFormatException e),System.out.println(Invalid integer entered!);,System.exit(-1);,catch(ArithmeticException e),System.out.println(Second number is 0,cannot do division!);,System.exit(-1);,异常处理简介,3.2.3 异常的处理(续),例3_1,4,53,运行结果,Enter the first number:,143,Enter the second number:,0,Second number is 0,cannot do division!,异常处理简介,3.2.3 异常的处理(续),例3_1,4,运行结果,54,对程序进行改进:重复提示输入,直到输入合法的数据。,import java.io.*;,public class ExceptionTester4,public static void main(String args),int result;,int number=new int2;,boolean valid;,for(int i=0;i2;i+),valid=false;,while(!valid),try,System.out.println(Enter number+(i+1);,numberi=,Integer.valueOf(Keyboard.getString().intValue();,valid=true;,catch(NumberFormatException e),(Invalid integer entered.Please tryagain.);,异常处理简介,3.2.3 异常的处理(续),例3_1,4,改进,55,try,result=number0/number1;,System.out.print(number0+/+number1+=+result);,catch(ArithmeticException e),System.out.println(Second number is 0,cannot do division!);,3.2.3 异常的处理(续),例3_1,4,改进,56,运行结果,Enter number 1,abc,Invalid integer entered.Please try again.,Enter number 1,efg,Invalid integer entered.Please try again.,Enter number 1,143,Enter number 2,abc,Invalid integer entered.Please try again.,Enter number 2,40,143/40=3,3.2.3 异常的处理(续),例3_1,4,运行结果,57,3.2.4 生成异常对象,生成异常对象,三种方式,由,Java,虚拟机生成,由,Java,类库中的某些类生成,在程序中生成自己的异常对象,也即是异常可以不是出错产生,而是人为地抛出,生成异常对象都是通过,throw,语句实现,生成的异常对象必须是,Throwable,或其子类的实例,throw new ThrowableObject();,ArithmeticException e=new ArithmeticException();,throw e;,58,生成异常对象举例,class ThrowTest,public static void main(String args),try throw new ArithmeticException();,catch(ArithmeticException ae),System.out.println(ae);,try throw new ArrayIndexOutOfBoundsException();,catch(ArrayIndexOutOfBoundsException ai),System.out.println(ai);,try throw new StringIndexOutOfBoundsException();,catch(StringIndexOutOfBoundsException si),System.out.println(si);,3.2.4 生成异常对象(续),例3_16,59,运行结果,3.2.4 生成异常对象(续),例3_16运行结果,60,3.2.5 声明自己的异常类,声明自己的异常类,除使用系统预定义的异常类外,用户还可声明自己的异常类,自定义的所有异常类都必须是,Exception,的子类,一般的声明方法如下,public class MyExceptionName extends SuperclassOfMyException,public MyExceptionName(),super(Some string explaining the exception);,61,声明当除数为零时抛出的异常类,DivideByZeroException,public class DivideByZeroException extends ArithmeticException,public DivideByZeroException(),super(Attempted to divide by zero);,import java.io.*;,public class Examp3_16,private static int quotient(int numerator,int denominator),throws DivideByZeroException,if(denominator=0)throw new DivideByZeroException();,return(numerator/denominator);,3.2.5 声明自己的异常类(续),例3_17,62,public static void main(String args),int number1=0,number2=0,result=0;,try,System.out.println(Enter the first number:);,number1=Integer.valueOf(Keyboard.getString().intValue();,System.out.println(Enter the second number:);,number2=Integer.valueOf(Keyboard.getString().intValue();,result=quotient(number1,number2);,catch(NumberFormatException e),System.out.println(Invalid integer entered!);,System.exit(-1);,catch(DivideByZeroException e),System.out.println(e.toString();,System.exit(-1);,System.out.println(number1+/+number2+=+result);,3.2.5 声明自己的异常类(续),例3_17,63,运行结果如下,Enter the first number:,140,Enter the second number:,0,DivideByZeroException:Attempted to divide by zero,3.2.5 声明自己的异常类(续),例3_17运行结果,64,3.3 方法重载,方法重载,一个类中名字相同的多个方法,这些方法的参数必须不同,,Java,可通过参数列表的不同来辨别重载的方法,或者参数个数不同,或者参数类型不同,返回值可以相同,也可以不同,重载的价值在于它允许通过使用一个方法名来访问多个方法,65,通过方法重载分别接收一个或几个不同数据类型的数据,class MethodOverloading,public void receive(int i),System.out.println(Receive one int parameter.);,System.out.println(i=+i);,public void receive(double d),System.out.printl
展开阅读全文