java答案第六章
《Java基础入门》-课后习题答案--1-6

第1章Java开发入门一、填空题1、Java EE、Java SE、Java ME2、JRE3、javac4、bin5、path、classpath二、选择题1、ABCD2、C3、D4、B5、B三、简答题1、面向对象、跨平台性、健壮性、安全性、可移植性、多线程性、动态性等。
2、JRE(Java Runtime Environment,Java运行时环境),它相当于操作系统部分,提供了Java程序运行时所需要的基本条件和许多Java基础类,例如,IO类、GUI控件类、网络类等。
JRE是提供给普通用户使用的,如果你只想运行别人开发好的Java程序,那么,你的计算机上必须且只需安装JRE。
JDK(Java Development Kit,Java开发工具包),它包含编译工具、解释工具、文档制作工具、打包工具多种与开发相关的工具,是提供给Java开发人员使用的。
初学者学习和使用Java语言时,首先必须下载和安装JDK。
JDK中已经包含了JRE部分,初学者安装JDK后不必再去下载和安装JRE了。
四、编程题public class HelloWorld {public static void main(String[] args) {System.out.println("这是第一个Java程序!");}}第2章Java编程基础一、填空题1、class2、true和false3、单行注释、多行注释、文档注释4、基本数据类型、引用数据类型5、1、2、4、86、& && | ||7、08、59、3410、56二、判断题1、错2、对3、错4、对5、错三、选择题1、AD2、AD3、C4、ABCD5、C 6 、A 7、AC 8、A 9、B 10、A四、程序分析题1、编译不通过。
int值4和b相加时,由于变量b的类型为byte,取值范围没有int类型大,存不下int类型的值,因此编译不通过。
解析JAVA程序设计第六章课后答案

第6章习题解答1.简述Java中设计图形用户界面程序的主要步骤。
对于设计图形用户界面程序而言,一般分为两个步骤:第一步,设计相应的用户界面,并根据需要对相关的组件进行布局;第二步,添加相关的事件处理,如鼠标、菜单、按钮和键盘等事件。
2.试说明容器与组件之间的关系。
组件(component)是图形用户界面中的各种部件(如标签、按钮、文本框等等),所有的组件类都继承自JComponent类。
容器(container)是用来放置其他组件的一种特殊部件,在java中容器用Container类描述。
3.阅读下面程序,说明其运行结果和功能。
//filename:MyFrame.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class MyFrame{public static void main(String agrs[]){JFrame f=new JFrame("简单窗体示例");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JLabel l=new JLabel("习题1");f.getContentPane().add(l,BorderLayout.CENTER);f.pack();f.setVisible(true);}}程序的运行结果如下:4.阅读下面程序,说明其运行结果和功能。
//filename:TestButton.javaimport java.awt.*;import javax.swing.*;public class TestButton extends JFrame{JButton b1,b2;TestButton(String s){super(s);b1=new JButton("按钮1");b2=new JButton("按钮2");setLayout(new FlowLayout());add(b1);add(b2);setSize(300,100);setVisible(true);}public static void main(String args[]){ TestButton test;test=new TestButton("测试按钮"); }}程序的运行结果如下:5.阅读下面程序,说明其运行结果和功能。
java答案第六章

Java语言程序设计第六章课后习题答案1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。
个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。
注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。
import java.io.*;public class test6_2{public static void main(String[] args) throws IOException { String fileName = "D:\\Hello.txt";File writer=new File(fileName);writer.createNewFile();BufferedWriter input = new BufferedWriter(newFileWriter(writer));input.write("Hello !\n");input.write("this is my first text file,\n");input.write("你还好吗?\n");input.close();}}运行结果:(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.// CopyMaker类import java.io.*;class CopyMaker {String sourceName, destName;BufferedInputStream source;BufferedOutputStream dest;int line;//打开源文件和目标文件,无异常返回trueprivate boolean openFiles() {try {source = new BufferedInputStream(newFileInputStream( sourceName ));}catch ( IOException iox ) {System.out.println("Problem opening " + sourceName );return false;}try {dest = new BufferedOutputStream(newFileOutputStream( destName ));}catch ( IOException iox ){System.out.println("Problem opening " + destName );return false;}return true;}//复制文件private boolean copyFiles() {try {line = source.read();while ( line != -1 ) {dest.write(line);line = source.read();}}catch ( IOException iox ) {System.out.println("Problem reading or writing" );return false;}return true;}//关闭源文件和目标文件private boolean closeFiles() {boolean retVal=true;try { source.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + sourceName );retVal = false;}try { dest.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + destName );retVal = false;}return retVal;}//执行复制public boolean copy(String src, String dst ) {sourceName = src ;destName = dst ;return openFiles() && copyFiles() && closeFiles();}}//test6_2public class test6_2{public static void main ( String[] args ) {String s1="lin.txt",s2="newlin.txt";if(new CopyMaker().copy(s1, s2))S ystem.out.print("复制成功");elseS ystem.out.print("复制失败");}}运行前的两个文本:lin.txt和newlin.txt(为空)运行后:3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。
《Java语言程序设计:基础篇》课后复习题答案-第六章

《Java语言程序设计:基础篇》课后复习题答案-第六章Chapter6Single-dimensional Arrays1.See the section"Declaring and Creating Arrays."2.You access an array using its index.3.No memory is allocated when an array is declared.The memory is allocated whencreating the array.x is60The size of numbers is304.Indicate true or false for the following statements:1.Every element in an array has the same type.Answer:True2.The array size is fixed after it is declared.Answer:False3.The array size is fixed after it is created.Answer:True4.The element in the array must be of primitive data type.Answer:False5.Which of the following statements are valid array declarations?int i=new int(30);Answer:Invaliddouble d[]=new double[30];Answer:Validchar[]r=new char(1..30);Answer:Invalidint i[]=(3,4,3,2);Answer:Invalidfloat f[]={2.3, 4.5, 5.6};Answer:Validchar[]c=new char();Answer:Invalid6.The array index type is int and its lowest index is0.a[2]7.(a)double[]list=new double[10];(b)list[list.length–1]=5.5;(c)System.out.println(list[0]+list[1]);(d)double sum=0;for(int i=0;i<list.length;i++)< p="">sum+=list[i];(e)double min=list[0];for(int i=1;i<list.length;i++)< p="">if(min>list[i])min=list[i];(f)System.out.println(list[(int)(Math.random()*list.length));(g)double[]={3.5, 5.5, 4.52, 5.6};8.A runtime exception occurs.9.Line3:the array declaration is wrong.It should be double[].The array needs tobe created before its been used.e.g.new double[10]Line5:The semicolon(;)at the end of the for loop heading should be removed.Line5:r.length()should be r.length.Line6:random should be random()Line6:r(i)should be r[i].10.System.arraycopy(source,0,t,0,source.length);11.The second assignment statement myList=new int[20]creates a new array andassigns its reference to myList.myList new int[10]Array myList new int[10]Arraynew int[20]Array12.False.When an array is passed to a method,the reference value of the array ispassed.No new array is created.Both argument and parameter point to the samearray.13.numbers is 0and numbers[0]is314.(A) ExecutingcreateArray in Line 6Space required for the main methodchar[] chars: refHeap Array of 100 charactersSpace required for the createArray methodchar[] chars: ref(B) After exitingcreateArray in Line 6Space required for themain methodchar[] chars: refHeapArray of 100charactersStack Stack (C) ExecutingdisplayArray in Line 10Space required for the main methodchar[] chars: refHeap Array of 100 charactersSpace required for the displayArray method char[] chars: ref(D) After exitingdisplayArray in Line10Space required for themain methodchar[] chars: refHeapArray of 100charactersStack Stack(E) Executing countLetters in Line 13 Space required for the main methodint[] counts: refchar[] chars: refHeap Array of 100 charactersSpace required for the countLetters method int[] counts: refchar[] chars: ref (F) After exitingcountLetters in Line 13Space required for themain methodint[] counts: refchar[] chars: refHeapArray of 100charactersStack StackArray of 26 integers Array of 26 integers(G) Executing displayCounts in Line 18Space required for the main methodint[] counts: refchar[] chars: refHeap Array of 100 charactersSpace required for the displayCounts methodint[] counts: ref (H) After exitingdisplayCounts in Line 18Space required for themain methodint[] counts: refchar[] chars: refHeapArray of 100charactersStack StackArray of 26 integers Array of 26 integers15.Only one variable-length parameter may be specified ina method and this parameter must be the last parameter.The method return type cannot be a variable-length parameter.16.The last oneprintMax(new int[]{1,2,3});is incorrect,because the array must of the double[] type.17.Omitted18.Omitted19.Omitted20Simply change(currentMaxlist[j])21Simply change list[k]>currentElement on Line9tolist[k]<currentelement< p="">22.You can sort an array of any primitive types except boolean.The sort method is void,so it does not return a new array.23.To apply java.util.Arrays.binarySearch(array,key),the array must be sorted in increasing order.24.Line1:list is{2,4,7,10}Line2:list is{7,7,7,7}Line3:list is{7,8,8,7}Line4:list is{7,8,8,7}</currentelement<></list.length;i++)<></list.length;i++)<>。
JAVA考试题库第六章

二 判断题
6-1.异常是一种特殊的运行错误的对象。(对) 6-2.异常处理可以使整个系统更加安全和稳定。(对) 6-3.异常处理是在编译时进行的。(错) 6-4.Java 语言中异常类都是 ng.Throwable 的子类。(对) 6-5.Throwable 类有两个子类:Error 类和 Exception 类。前者由系统保留,后者供应用程序使用。(对) 6-6.异常通常是指 Error 类和 Exception 类。(错) 6-7.Exception 类只有一个子类为 RuntimeException。(错) 6-8.在异常处理中,出现异常和抛出异常是一回事。(错) 6-9.运行时异常是在运行时系统检测并处理的。(错) 6-10.使用 try-catch-finally 语句只能捕获一个异常。(错) 6-11.捕获异常时 try 语句后面通常跟有一个或多个 catch()方法用来处理 try 块内生成的异常事件。(对) 6-12.使用 finally 语句的程序代码为该程序提供一个统一的的出口。(对) 6-13.抛出异常的方法说明中要加关键字 throws,并在该方法中还应添加 throw 语句。(对) 6-14.创建异常类时要给出该异常类的父类。(对) 6-15.如果异常类没有被捕获将会产生不正常的终止。(对) 三 分析程序的输出结果
6-1.Exer6_1.java public class Exer6_1 { public static void main(String args[] )
java考试题库第六章

java考试题库第六章第六章异常和异常处理一选择题6-1.下列关于异常的描述中,错误的是(B)A.异常是一种经过修正后程序仍可执行的错误B.异常是一种程序在运行中出现的不可恢复执行的错误C.不仅Java语言有异常处理,C++语言也有异常处理D.出现异常不是简单结束程序,而是执行某种处理异常的代码,设法恢复程序的执行6-2.下列关于异常处理的描述中,错误的是(D)A.程序运行时异常由Java虚拟机自动进行处理B.使用try-catch-finally语句捕获异常C.使用throw语句抛出异常D.捕获到的异常只能用当前方法中处理,不能用其他方法中处理6-3.下列关于try-catch-finally语句的描述中,错误的是(A)A.try语句后面的程序段将给出处理异常的语句B.catch()方法跟在try语句后面,它可以是一个或多个C.catch()方法有一个参数,该参数是某种异常类的对象D.finally语句后面的程序段总是被执行的,该语句起到提供统一接口的作用6-4.下列关于抛出异常的描述中,错误的是(D)A.捕捉到发生的异常可在当前方法中处理,也可以抛到调用该方法的方法中处理B.在说明要抛出异常的方法时应加关键字throw<异常列表>C.<异常列表>中可以有多个用逗号分隔的异常D.抛出异常的方法中要使用下述抛出异常语句:throw<异常名>;其中,<异常名>是异常类的类名6-5.下列关于用户创建自己的异常描述中,错误的是(D)A.创建自己的异常应先创建一个异常类B.为实现抛出异常,须在可能抛出异常的方法中书写throw语句C.捕捉异常的方法是使用try-catch-finally语句格式D.使用异常处理不会使整个系统更加安全和稳定二判断题6-1.异常是一种特殊的运行错误的对象。
(对)6-2.异常处理可以使整个系统更加安全和稳定。
(对)6-3.异常处理是在编译时进行的。
《Java程序设计案例教程》第六章练习答案

第6章共享与数据保护一、单选题1.已知print()函数是一个类的常成员函数,无返回值,下列正确的原型声明(A)。
A.void print()const;B.const void print();C.void const print();D.void print(const);2.有以下类的说明,请指出错误的地方(A)。
class CSample{const int a=2.5;//Apublic:CSample();//BCSample(int val);//C~CSample();//D};3.下列关于静态成员的描述中,错误的是(C)。
A.静态成员都使用static来说明B.静态成员属于某一个类,而不专属于某一对象C.静态成员只能用类名加作用域运算符引用,不可以通过对象来引用D.静态数据成员的初始化是在类体外进行的4.下列关于常成员的描述中,错误的是(C)。
A.常成员是用关键字const来说明的B.常成员有常数据成员和常成员函数两种C.常数据成员的初始化可以在定义类的类体内用形如const int a=10;的方式进行D.常数据成员的值是不可以改变的5.有以下类的说明,下列哪一种构造函数无法对常数据成员a正确初始化(C)。
class CSample{const int a;public://构造函数代码,见下面的选项};A.CSample():a(24){}B.CSample(int m):a(m){}C.CSample(){a=24;}D.CSample(int m):a(m+24){}6.设类AA内定义了一个int型的静态数据成员a,下列哪种方式对a的初始化正确(D)。
A.在类AA的定义体内用static int a=20;B.在类AA的定义体外单独用语句static int a=20 ;C.在类AA的定义体外单独用语句static int AA∷a=20;D.在类AA的定义体外单独用语句int AA∷a=20;7.关于静态成员函数,下列说法不正确的是(A)。
《Java语言程序设计-基础篇》答案-第06章

第6章 类与对象复习题6.1 答: 略6.2答: 略6.3答: 构造方法 ShowErrors(int) 没有定义.原因是默认的构造函数是没有参数的.6.4答: 略6.5答: 变量c 没有初始化,也可以说是没有将对象引用到实例.即c 为null. 6.6 答: 构造函数A()没有定义.原因是类中有了有参的构造方法A(String s),但没有无参构造方法,而系统不会再提供默认的构造函数A()。
系统找不到默认的构造函数.在这种情况下,如果还要用A(),则需要重新定义. 6.7 答:构造函数C(double)没有定义.原因是默认的构造函数是没有参数的. 6.8 答:输出:false;原因是boolean 类型的变量如果没有初始化,则默认初始值为false; 6.9 答:方法x()没有定义;6.10答:略6.11答:略6.12答:输出:1.0;私有变量可以被类里的成员方法访问.6.13答:略6.14答:略6.15答:传递基本类型参数值的变化不能被带回,而引用类型参数的变化可以带回.输出: count is 101 times is 06.16答:After swap1 : circle1= 1.0 circle2=2.0After swap2 : circle1= 2.0 circle2=1.0课后答案网ww w.kh da w .c om6.17答:a[0]= 1 a[1]= 2 (a)a[0]= 2 a[1]= 1 (b)e1 = 2 e2= 1 (c)t1's i = 2 and j= 1 (d)t2's i = 2 and j= 1第四个值得注意,因为 i 为静态的,因此经过二次实例化后,i 就变成2了。
而j 是没有变的,一直为1。
6.18答:System.out .println(f.i);System.out .println(f.s ); f.imethod(); f.smethod ();System.out .println(Foo.s ); Foo.smethod ();但静态成员最好直接用类访问.像 System.out .println(f.s ); f.smethod ();6.19答:i + j is 23k is 2 j is 06.20答:不能在静态方法中调用非静态方法,不能在静态方法中调用非静态变量.反之可以.错误是:不能调用method1(),不能调用c.6.22答:错误没有,但会提出警告:p 不明确,这里应该用this.p;6.23答:第一个输出为:null,因为一个对象的默认值是null,而第二个输出有错,原因是没有将对象引用到实例,即dates[0]为空课后答案网ww w.kh da w .c om。
JAVA语言程序设计基础课后习题第六章

JAVA语⾔程序设计基础课后习题第六章//exercise 6.1package second;import java.util.Scanner;public class first {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);System.out.print("Enter the number of students:");int number=in.nextInt();System.out.print("Enter "+number+" scores:");int []score=new int[number];getscores(score);int best=max(score);for(int i=0;i<number;i++){System.out.println("Student "+i+" score is "+score[i]+" and grade is "+grade(score[i],best));}}public static void getscores(int []score){Scanner in=new Scanner(System.in);for(int i=0;i<score.length;i++){score[i]=in.nextInt();}}public static int max(int[] score){int max=score[0];for(int i=0;i<score.length;i++){if(max<score[i])max=score[i];}return max;}public static char grade(int score,int max){if(score>=max-10)return 'A';else if(score>=max-20)return 'B';else if(score>=max-30)return 'C';else if(score>=max-40)return 'D';elsereturn 'F';}}//exercise 6.2package second;import java.util.Scanner;public class second {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubint []number=get();reverseprint(number);}public static int[] get(){Scanner in=new Scanner(System.in);int[] number=new int[10];System.out.println("input 10 number:");for(int i=0;i<number.length;i++){number[i]=in.nextInt();}return number;}public static void reverseprint(int[]Array){for(int i=Array.length-1;i>=0;i--){System.out.print(Array[i]+" ");}}}//exercise 6.3package second;import java.util.Scanner;public class third {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);int[] newarray=new int[100];int temp;for(int i=0;i<newarray.length;i++){newarray[i]=0;}System.out.print("Enter the integers between 1 and 100:");while((temp=in.nextInt())!=0){newarray[temp]++;}resultprint(newarray);}public static void resultprint(int []array){for(int i=0;i<array.length;i++){if(array[i]==1)System.out.println(i+" occurs "+array[i]+" time");if(array[i]!=0&&array[i]!=1)System.out.println(i+" occurs "+array[i]+" times");}}}//exercise 6-4package first;import java.util.Scanner;public class first {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);int []score=new int[100];int i=0,sum=0,count=0;System.out.print("input integer:");while((score[i]=in.nextInt())!=-1){sum+=score[i++];count++;}int average=sum/count;int big=0,small=0;for(int j=0;j<count;j++){if(score[j]<average)small++;elsebig++;}System.out.println("average is "+average);System.out.println("better than average is "+big);System.out.println("small than average is "+small);}}//exercise 6-5package first;import java.util.Scanner;public class second {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub Scanner in=new Scanner(System.in); System.out.print("Enter ten numbers:");int []integer=new int[10];int count=0;for(int i=0;i<10;i++){boolean judge=false;int temp=in.nextInt();for(int j=0;j<count;j++){if(temp==integer[j]){judge=true;}}if(!judge){integer[count++]=temp;}}System.out.print("input integer:");for(int i=0;i<count;i++){System.out.print(integer[i]+" ");}}}//exercise 6-7package first;public class third {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubint []counts=new int[10];for(int i=0;i<100;i++){int random=(int)(Math.random()*10); counts[random]++;}for(int i=0;i<10;i++){System.out.print(i+" ");}System.out.println();for(int i=0;i<10;i++){System.out.print(counts[i]+" ");}}}//exercise 6-8package first;public class fourth {/*** @param args*/public static int average(int[]array){int sum=0,count=0;for(int i=0;i<array.length;i++){sum+=array[i];count++;}return sum/count;}public static double average(double []array){double sum=0;int count=0;for(int i=0;i<array.length;i++){sum+=array[i];count++;}return sum/count;}}//exercise 6-9package first;public class fifth {/*** @param args*/public static double min(double []array){double min=array[0];for(int i=0;i<array.length;i++){if(min>array[i])min=array[i];}return min;}}//exercise 6-10package first;public class seventh {/*** @param args*/public static int indexOfSmallestElement(double[] array){ double min=array[0];for(int i=0;i<array.length;i++){if(min>array[i])min=array[i];}for(int i=0;i<array.length;i++){if(min==array[i])return i;}return 0;}}。
Java基础第6章编程题答案

第六章集合编程题1.遍历一个LinkedList集合,写一个可以删除所有与“tom”相同的元素的静态方法。
(集合中的元素自行添加)注意:不要使用for循环遍历删除,会出现删除不干净的情况【参考答案】import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList;public class Test {public static void main(String[] args) {LinkedList<String> list=new LinkedList<String>();list.add("tom");list.add("jack");list.add("jone");list.add("tom");System.out.println(list);removes(list,"tom");System.out.println(list);}public static void removes(LinkedList<String> list, String s) {Iterator iterator = list.iterator();while (iterator.hasNext()) {String str = (String) iterator.next();if (str.equals(s)) {iterator.remove();}}}}2.如何判断两个集合是否有交集,并打印出他们的交集提示:判断这两个集合是否包含相同的对象或元素,可以使用retainAll方法:oldCourses.retainAll(newCoures)。
如果存在相同元素,oldCourses中仅保留相同的元素。
第6章 习题答案

第6章习题
1. 关键字__throws__用来声明方法可能抛出的异常,关键字throw用来在方法中抛出异常。
2. 要捕获异常,使用的关键字__try__和__catch__。
3. 无论有无异常发生,始终要被执行的代码放在___finally___块中。
4. 简述Java程序中的三种错误?
答: 对于一个程序来说,可能会发生三种错误,语法错误、运行时错误和逻辑错误。
(1)语法错误的产生是在我们编写代码的过程中可能输入的字符错误,不符合相应的命令格式等;
(2)运行时错误是程序在运行中出现意料不到情况,如除数为零,数组越界等;
(3)逻辑错误是程序的运行结果和我们预想的结果不一致,这是一种难以调试的错误。
5. 简述使用try...catch处理异常的三种情况?
答:(1)第一种情况(try代码块不会产生异常) ,此时执行完try代码块,转而执行try…catch后的代码块;
(2)第二种情况(try代码块产生异常,并且与捕获的异常类型匹配),此时执行到产生异常代码时,转而执行相匹配的catch语句块,之后执行try…catch后的代码块;
(3)第三种情况(try代码块产生异常,并且与捕获的异常类型不匹配),当执行到产生异常的代码时,程序被中断。
Java程序设计案例教程 习题答案 第6章 集合

第6章集合类一.填空
1.Collection
2.hashNext() next()
3.Array List LinkedList, HashSet> TreeSet, HashMap、TreeMap
4.Key> Value
5.数组二.判断
1.错
2.对
3.错
4.对5,对三.选择
1.BC
2.B
3.ABCD
4.D
5.B
6.C四.简答
1. List的特点是元素有序、可重复。
List接口的主耍实现类有ArrayList和LinkedListo Set的特点是元素无序、不可重复。
Set接口的主要实现类有HashSet和TreeSeto Map的特点是存储的元素是键(Key)、值(Value)映射关系,元素都是成对出现的。
M叩接口的主要实现类有HashMap和TreeMap o
2.由于ArrayList集合的底层是使用一个数组来保存元素,在增加或删除指定位置的元素时,会导致创立新的数组,效率比拟低,因此不适合做大量的增删操作。
但这种数组的结构允许程序通过索引的方式来访问元素,因此使用ArrayList集合查找元素很便捷。
五.编程。
JAVA期末复习题及答案——第六章

JAVA期末复习题及答案——第六章一.填空题1.Java中的异常类对象是Error类或Exception类的对象,这两个类中 Error 类的对象不会被Java的应用程序捕获和抛出。
2.在下列程序的下划线处,填入适当语句使程序能正确执行并输出异常栈信息public class ThrowableException{public static void main(String args[]){try{throw new Throwable(“这是本人定义的异常”);}catch(Throwable e){System.out.println(“e.toString:”+e.toString());System.out.println(“e.printStackTrace():”);System.out.println(e.printStackTrace()) ;}}}二.选择题1.下列关于finally的说法正确的是:BA、如果程序在前面的catch语句中找到了匹配的异常类型,将不执行finally 语句块B、无论程序是否找到匹配的异常类型,都会去执行finally语句块中的内容C、如果在前面的catch语句块中找到了多个匹配的异常类型,将不执行finally 语句块D、只要有catch语句块,任何时候都不会执行finally语句块2.关于多个catch语句块的异常捕获顺序的说法正确的是:DA、父类异常和子类异常同时捕获B、先捕获父类异常C、先捕获子类异常D、依照catch语句块的顺序进行捕获,只能捕获其中的一个3.关于Java 异常,下列说法错误的是(D)A.异常是定义了程序中遇到的非致命的错误,而不是编译时的语法错误B.try……catch语句中对try 内语句监测,如果发生异常,则把异常信息放入对象e 中C.throws 用来表示一个方法有可能抛出异常给上一层,则在调用该方法时必须捕捉异常,否则无法编译通过D.主函数不可以使用 throws 抛出异常4.所有异常的父类是(B)。
java chapter 6(带作业题)

• 程序第一次引用含有静态变量的类时,将静态变量 分配存储空间;
• 在方法中声明的局部变量不能具有静态属性。 • Java程序的main方法必须用static修饰符进行说明, 使解释器执行main方法时,不用实例化含main方 法的类。
8
• 6.4.2 同一个类的对象之间的依赖性 • 即一个类对象与本类的其他对象交互。要实现这一操作, 可以将一个类的对象作为一个参数传递给本类的一个方法, 使得该方法可以对作为参数得到的对象进行操作。 • 例如: str3 = str1.concat( str2) ;
例题 6.3 例题 6.4
9
• 6.4.3 聚合(has a )关系 • 一个聚合对象由其他的对象组成,形成一个”has a”关系 • 一个聚合对象的定义是:将其他对象的引用作为自己的实 例数据的对象。 • 聚合关系是依赖关系的特殊类型,即类A被类B定义为类B 的一部分时,类A便依赖类B,类B就是聚合类。 • 一个聚合类通常要调用其组成部分类的方法。 • 例题 6.5 • 例题 6.6 • 例题 6.7
14
• 6.5.1 Comparable接口 • 该接口定义在ng包中,该接口中只有一个方法 compareTo,该方法的参数是一个对象,返回值为整型值。 • Comparable接口的目的是提供对两个对象进行比较的通 用机制。 • 例如: • if (pareTo(obj2) < 0) • system.out.println (“obj1 is less than obj2”); • 6.5.2 Iterator接口 • 也定义在Java标准类库中,由代表一个对象结合的类使用, 主要提供了在一个对象集合中每操作一次移动到下一个对 象的方法。 • 该接口中的两个方法是hasNext和next方法。
JAVA程序设计案例教程(第二版)周怡、张英主编。第6章 习题答案

的类可以通过关键字 implements 实现多个接口。
(√)
5.Math 类是 final 类,因此在被其他类继承时其中的方法不能被重,正确的是(A)。
A.类是变量和方法的集合体
B.数组是无序数据的集合
C.抽象类可以实例化
D.类成员数据必须是共有的
2.下面对形参的说法中,正确的是(C)。
4.为什么要将类封装起来?封装的原则是什么? 答:因为封装的类之间互相独立、互不干扰,但可以通过规定的数据接口来进行数据交换,即能 保证数据的安全又能提高类之间相互组合的高效性。
一、将数据和对数据的操作组合起来构成类,类是一个不可分割独立单位。 二、类中既要提供与外部联系的方法,同时又要尽可能隐藏类的实现细节和保护自身数据 的安全性。
3.Java 设置了几种类成员的访问权限?各表示什么含义?
答:(1)公有的(public):说明该类成员可被所有类的对象使用 (2)保护的(protected):说明该类成员能被同一类中的其他成员,或其他子类成员,或同一 包中的其他类访问,不能被其他包的非子类访问。 (3)默认的(缺省):说明该类成员能被同一类中的其他成员,或同一包中的其他类访问,但 不能被其他包的类访问。 (4)私有的(private):说明该类成员只能被同一类中的其他成员访问,不能被其他类的成员 访问,也不能被子类成员访问。
译时多态性。 方法的覆盖:在子类中重定义父类的同名方法。方法覆盖表现为父类与子类之间的方法的
多态性,其中形参表、返回值类型也必须相同,且子类方法不能有比父类方法更严格的访问权 限。可以为编译时多态性或运行时多态性。
6.什么叫构造方法?构造方法的作用是什么?
答:构造方法是对象实例化时完成对象及其成员变量的初始化时所调用的一种特殊的方法。 构造方法的作用是在使用 new 关键字创建类的实例的时候被调用来对实例进行初始化。
Java语言程序设计(一)课后习题第六章(附答案)

·getlmaginaryPart()获得复数对象的虚部。
·setRealPart(doubled)把当前复数对象的实部设置为给定的形参的数字。
·setlmaginaryPart(doubled)把当前复数对象的虚部设置为给定形参的数字。
·complexAdd(ComplexNumberc)当前复数对象与形参复数对象相加,所得的结果也是复数值,返回给此方法的调用者。
+ cNumber_2.toString() + “等于“
+ cNumber_plexMinus(cNumber_2).toString());
System.out.println(cNumber_1.toString() + “减“
+ d + “等于“
+ cNumber_plexMinus(d).toString());
System.out.println(cNumber_1.toString() + “乘“
+ cNumber_2.toString() + “等于“
+ cNumber_plexMulti(cNumber_2).toString());
System.out.println(cNumber_1.toString() + “乘“
{
public abstract string subMethod();
}
参考答案:
1. trueLeabharlann 2.A3.答:子类重新定义父类中已经存在的方法,称为方法的覆盖。注意:方法覆盖与域的隐藏不同。子类重新定义父类已有的域,并不能完全取代它从父类那里继承的同名的域,这个域仍然占用子类的内存空间,在某些情况下会被使用;而当子类重新定义父类的方法时,从父类那里继承来的方法将被新方法完全取代,不再在子类的内存空间中占一席之地。与方法的覆盖不同,重载不是子类对父类同名方法的重新定义,而是在一个类中定义了同名的不同方法。
JAVA第六章习题

第六章异常和异常处理一、选择题1、下列关于异常和异常类的描述中,错误的是 D 。
A.异常是某种异常类的对象B.异常类代表一种异常事件C.异常对象中包含有发生异常事件的类型等重要信息D.对待异常的处理就是简单地结束程序2、下列关于异常处理的描述中,错误的是 C 。
A.程序运行时出现的异常是通过系统默认的异常处理程序进行处理的。
B.在程序中可以使用try-catch语句捕捉异常和处理异常事件C.对于捕获的异常只能在当前方法中处理D.使用throw语句可将异常抛出到调用当前方法的方法中处理二、简答题1、简述Java的异常处理机制。
Java系统中定义一些用来处理异常的类,称为异常类,该类中通常包含产生某种异常的信息和处理异常的方法等内容。
当程序运行中发生了可识别的异常时(该错误有一个异常类与之相对应时)系统就会产生一个相应的该异常类的对象,简称异常。
系统中一旦产生了一个异常,便去寻找处理该种异常的处理程序,以保证不产生死机,从而保证了程序的安全运行。
这就是Java的异常处理机制.三、写出运行结果题1、public class Exam6_4{ public static void main(String args[]){ fun(0);fun(1);fun(2);fun(3);}static void fun(int i){ System.out.println("调用方法:fun"+i);try{if(i==0) System.out.println("没有异常");else if(i==1){int a=0; int b=10; b/=a;}else if(i==2){int m[]=new int[5]; m[5]=100;}else if(i==3){String str="56k9"; intn=Integer.parseInt(str);}}catch(ArithmeticException e){System.out.println("捕捉异常:"+e.getMessage());} catch(ArrayIndexOutOfBoundsException e){System.out.println("捕捉异常:"+e);}catch(NumberFormatException e){System.out.println("捕捉异常:"+e);}finally{System.out.println("处理完毕! ");}}}2、public class Exam6_5{ public static void main(String args[]){ try{fun1();}catch(ArithmeticException e){System.out.println("捕捉异常:"+e.getMessage());} try{fun2( );}catch(ArrayIndexOutOfBoundsException e){System.out.println("捕捉异常:"+e);}finally {System.out.println("处理完毕! ");}}static void fun1() throws ArithmeticException{ System.out.println("调用方法:fun1");int a=0; int b=10; b/=a;throw new ArithmeticException();}static void fun2() throws ArrayIndexOutOfBoundsException { System.out.println("调用方法:fun2");int m[]=new int[5]; m[5]=100;throw new ArrayIndexOutOfBoundsException();}}。
Java实战经典(第六章课后题答案)

public float getFoot(){ return this.foot ;
} public float getHeight(){
return this.height ; } } class Cycle extends Shape{ private float radius ; private static final float PI = 3.1415926f ; public Cycle(){} public Cycle(float radius){
4
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java语言程序设计第六章课后习题答案1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。
个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。
注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。
import java.io.*;public class test6_2{public static void main(String[] args) throws IOException { String fileName = "D:\\Hello.txt";File writer=new File(fileName);writer.createNewFile();BufferedWriter input = new BufferedWriter(newFileWriter(writer));input.write("Hello !\n");input.write("this is my first text file,\n");input.write("你还好吗?\n");input.close();}}运行结果:(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.// CopyMaker类import java.io.*;class CopyMaker {String sourceName, destName;BufferedInputStream source;BufferedOutputStream dest;int line;//打开源文件和目标文件,无异常返回trueprivate boolean openFiles() {try {source = new BufferedInputStream(newFileInputStream( sourceName ));}catch ( IOException iox ) {System.out.println("Problem opening " + sourceName );return false;}try {dest = new BufferedOutputStream(newFileOutputStream( destName ));}catch ( IOException iox ){System.out.println("Problem opening " + destName );return false;}return true;}//复制文件private boolean copyFiles() {try {line = source.read();while ( line != -1 ) {dest.write(line);line = source.read();}}catch ( IOException iox ) {System.out.println("Problem reading or writing" );return false;}return true;}//关闭源文件和目标文件private boolean closeFiles() {boolean retVal=true;try { source.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + sourceName );retVal = false;}try { dest.close(); }catch ( IOException iox ) {System.out.println("Problem closing " + destName );retVal = false;}return retVal;}//执行复制public boolean copy(String src, String dst ) {sourceName = src ;destName = dst ;return openFiles() && copyFiles() && closeFiles();}}//test6_2public class test6_2{public static void main ( String[] args ) {String s1="lin.txt",s2="newlin.txt";if(new CopyMaker().copy(s1, s2))S ystem.out.print("复制成功");elseS ystem.out.print("复制失败");}}运行前的两个文本:lin.txt和newlin.txt(为空)运行后:3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。
// memory存储类import java.io.*;import java.util.Random;public class memory {private String name;private int count;private int Max;private int Min;public memory(String n,int c,int min,int max){=n;this.count=c;this.Min=min;this.Max=max;}public void startmemory(){try{FileWriter out=new FileWriter(name);int limit=Max-Min;Random random = new Random();for (int i=1;i<=count;i++){int number=Min+random.nextInt(limit);System.out.print(number);System.out.print(" ");out.write(number+" ");}out.close();}catch(IOException iox){System.out.println("方法startmemory()有问题");}}}//test6_3import java.io.*;import java.util.Scanner;public class test6_3 {public static void main(String[] args) throws IOException{ //BufferedReaderString fileName;int count,min,max;Scanner in = new Scanner(System.in);System.out.println("输入要存储的文件名");fileName=in.next();System.out.println("输入随机数个数");count=in.nextInt();System.out.println("输入随机数最小值");min=in.nextInt();System.out.println("输入随机数最大值");max=in.nextInt();memory M=new memory(fileName,count,min,max);M.startmemory();}}}运行结果:naruto文件存储二进制数:4.分别使用FileWriter和BufferedWriter往文件中写入10万个随机数,比较用时的多少。
//FileWriter方法import java.io.*;public class fileWriter {public static void main(String[] args) throws IOException{ long time = System.currentTimeMillis();//当前时间FileWriter filewriter=new FileWriter("filewriter.txt");int number;for(int i=1;i<=100000;i++){number=(int)(Math.random()*10000);filewriter.write(number+" ");}filewriter.close();time=System.currentTimeMillis()-time;//时间差System.out.println("用时为:"+time+"微秒.");}}运行结果://BufferedWriter方法import java.io.*;public class bufferedWriter {public static void main(String[] args) throws IOException{ long time = System.currentTimeMillis();//当前时间BufferedWriter filewriter=new BufferedWriter(newFileWriter("filewriter.txt"));int number;for(int i=1;i<=100000;i++){number=(int)(Math.random()*10000);filewriter.write(number+" ");}filewriter.close();time=System.currentTimeMillis()-time;//时间差System.out.println("用时为:"+time+"微秒.");}}运行结果:有用时可知:BufferedWriter比FileWriter写入的速度快, 当需要写入大量内容,前者效率高。