java第五章习题及答案
- 格式:doc
- 大小:55.50 KB
- 文档页数:4
第5章 数组复习题5.1 答:(略)5.2 答:使用数组名和下标。
如:arrayName[index]5.3 答:声明数组时不为数组分配内存,使用new 运算符为数组分配内存。
输出结果: x is 60The size of numbers is 305.4 答:依次为:对、错、对、错5.5 答:有效的数组名分别是:d, f, r5.6 答:整数,05.7 答:a[2]5.8 答:出现下标越界错误,具体是:ArrayIndexOutOfBoundsException。
5.9 答:第3行改为:double[] r = new double[100]; 第5行的r.length()改为:r.length 第6行的r(i)改为:r[i]5.10 答:语句如下:int[] t = new int[source.length];System.arraycopy(source, 0, t, 0, source.length);5.11 答:不是修改数组大小,而创建一个新数组,并用myList 去引用。
5.12 答:不正确。
是将数组地址传递给方法形参。
5.13 答:输出如下:numbers is 0 and numbers[0] is 35.14 答:数组存放在堆(heap)中。
第2问参见P144图5-7。
5.15 - 5.18 (略)5.19 答:int[] matrix = new int[4][5];课后答案网ww w.kh da w .c om5.20 答:可以。
5.21 答:输出:array[0][1] is 2课后答案网ww w.kh da w .c om。
习题一、选择题1. 面向对象程序设计的基本特征是(BCD)。
(多选)A.抽象B.封装C.继承D.多态2.下面关于类的说法正确的是(ACD)。
(多选)A.类是Java 语言中的一种复合数据类型。
B.类中包含数据变量和方法。
C.类是对所有具有一定共性的对象的抽象。
D.Java 语言的类只支持单继承。
上机指导1.设计银行项目中的注册银行用户基本信息的类,包括账户卡号、姓名、身份证号、联系电话、家庭住址。
要求是一个标准Java类(数据私有,提供seter/getter),然后提供一个toString方法打印该银行用户的信息。
答:源代码请参见“CH05_LAB\src\com\inspur\ch05\BankUser.java”2.设计银行项目中的帐户信息,包括帐户卡号、密码、存款,要求如“练习题1”。
答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Account.java”3.设计银行项目中的管理员类,包括用户名和密码。
要求如“练习题1”。
答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Manager.java”4.创建一个Rectangle类。
添加两个属性width、height,分别表示宽度和高度,添加计算矩形的周长和面积的方法。
测试输出一个矩形的周长和面积。
答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Rectangle.java”5.猜数字游戏:一个类A有一个成员变量v,有一个初值100。
定义一个类,对A类的成员变量v进行猜。
如果大了则提示大了,小了则提示小了。
等于则提示猜测成功。
答:源代码请参见“CH05_LAB\src\com\inspur\ch05\Guess.java”6.编写一个Java程序,模拟一个简单的计算器。
定义名为Computer的类,其中两个整型数据成员num1和num1,编写构造方法,赋予num1和num2初始值,再为该类定义加、减、乘、除等公有方法,分别对两个成员变量执行加减乘除的运算。
第五章多线程选择题1. 线程调用了sleep()方法后,该线程将进入( C )状态。
A.可运行状态B.运行状态C.阻塞状态D.终止状态2. 关于java线程,下面说法错误的是(D)A.线程是以CPU为主体的行为B. java利用线程使整个系统成为异步C.创建线程的方法有两种:实现Runnable接口和继承Thread类D. 新线程一旦被创建,它将自动开始运行3.在java语言中,临界区可以是一个语句块,或者是一个方法,并用(A )关键字标识。
A.synchronizedB.includeC.importD.Thread4. 线程控制方法中,yield()的作用是(D)A.返回当前线程的引用B.使比其低的优先级线程执行C.强行终止线程D.只让给同优先级线程运行5. java用(A)机制实现了进程之间的异步执行A.监视器B.虚拟机C.多个CPUD.异步调用6. 下面代码运行的结果是什么?(D)public class MyThread implements Runnable {String myString = "Yes ";public void run() {this.myString = "No ";}public static void main(String[] args) {MyThread t = new MyThread();new Thread(t).start();for (int i=0; i < 10; i++)System.out.print(t.myString);}}A. 打印yes yes yes yes yes yes B. 打印no no no no no no no noC. 打印yes no yes no ye no ye no D. 不确定二、填空题1.____多线程____是java程序的并发机制,它能同步共享数据、处理不同的事件。
Chapter5Methods1.At least three benefits:(1)Reuse code;(2)Reduce complexity;(3)Easy to maintain.See the Sections5.2and5.3on how to declare and invoke methods.What is thesubtle difference between“defining a method”and“declaring a variable”?A declaration usually involvesallocating memory to store a variable,but a definitiondoesn’t.2.void3.Yes.return(num1>num2)?num1:num2;4.True:a call to a method with a void return type is always a statement itself.False:a call to a value-returning method is always a component of an expression.5.A syntax error occurs if a return statement is not used to return a value in a value-returning method.You can have a return statement in a void method,whichsimply exits the method.But a return statement cannot return a value such asreturn x+y in a void method.6.See Section5.2.puting a sales commission given the sales amount and the commission ratepublic static double getCommission(double salesAmount,doublecommissionRate)Printing a calendar for a monthpublic static void printCalendar(int month,int year)Computing a square rootpublic static double sqrt(double value)Testing whether a number is even and return true if it ispublic static boolean isEven(int value)Printing a message for a specified number of timespublic static void printMessage(String message,int times)Computing the monthly payment,given the loan amount,number of years,and annual interest rate.public static double monthlyPayment(double loan,intnumberOfYears,double annualInterestRate)Finding the corresponding uppercase letter given a lowercase letter.public static char getUpperCase(char letter)8.Line2:method1is not defined correctly.It does not have a return type or void.Line2:type int should be declared for parameter m.Line7:parameter type for n should be double to match method2(3.4).Line11:if(n<0)should be removed in method,otherwise a compile error is reported.9.public class Test{public static double xMethod(double i,double j){ while(i<j){j--;}return j;}}10.You pass actual parameters by passing the right type of value in the right order.The actual parameter can have the same name as its formal parameter.11."Pass by value"is to pass a copy of the value to the method.(A)The output of the program is0,because the variable max is not changed byinvoking the method max.(B)224248248162481632248163264(C)Before the call,variable times is3n=3Welcome to Java!n=2Welcome to Java!n=1Welcome to Java!After the call,variable times is3(D)12121421i is 512.Just before max is invoked.Space required for the main methodmax: 0Just entering max.Space required for the max methodmax: 0value2: 2 value1: 1Just before max is returnedSpace required for the main methodmax: 0Space required for the max methodmax: 2value2: 2 value1: 1 Space required for the main methodmax: 0Space required for the main methodmax: 0Right after max is returned13.Two methods with the same name,defined in the same class,is called method overloading.It is fine to have same method name,but different parameter types.You cannot overload methods based on return type,or modifiers.14.Methods public static void method(int x)and public static int method(int y)have the same signature method(int).15.Line 7:int n =1is wrong since n is already declared in the method signature.16.True17.(a)34+(int)(Math.random()*(55–34))(b)(int)(Math.random()*1000)(c)5.5+(Math.random()*(55.5–5.5))(d)(char)(‘a’+(Math.random()*(‘z’–‘a’+1))18.Math.sqrt(4)= 2.0Math.sin(2*Math.PI)=0Math.cos(2*Math.PI)=1Math.pow(2,2)= 4.0Math.log(Math.E)=1Math.exp(1)= 2.718Math.max(2,Math.min(3,4))=3 Math.rint(-2.5)=-2.0Math.ceil(-2.5)=-2.0Math.floor(-2.5)=-3.0Math.round(-2.5f)=-2Math.round(-2.5)=-2Math.rint(2.5)= 2.0Math.ceil(2.5)= 3.0Math.floor(2.5)= 2.0Math.round(2.5f)=3Math.round(-2.5)=-2Math.round(Math.abs(-2.5))=3。
一.程序设计题1.定义一个汽车类Car,要求如下:1)属性包括:汽车品牌brand(String类型)、颜色color(String类型)和速度speed(double类型),并且所有属性为私有。
2)至少提供一个有参的构造方法(要求品牌和颜色可以初始化为任意值,但速度的初始值必须为0)。
3)为私有属性提供访问器方法。
注意:汽车品牌一旦初始化之后不能修改。
定义测试类CarTest,在其main方法中创建一个品牌为“benz”、颜色为“black”的汽车。
public class Car{private String brand;private String color;private double speed;public Car(String brand,String color){this.brand=brand;this.color=color;}public String getColor(){return color;}public void setColor(String color){this.color=color;}public double getSpeed(){return speed;}public void setSpeed(double speed){this.speed=speed;}public String getBrand(){return brand;}}public class CarTest{public static void main(String[]args){Car c1=new Car("benz","black");}}2.定义一个图书类Book,要求如下:1)属性包括:书名name(String类型)、作者author(String类型),单价price(double类型),数量amount(int类型),并且所有属性为私有。
5_1public class Exercise01 {public static void main(String[] args) {final int PENTAGONAL_NUMBERS_PER_LINE = 10;final int PENTAGONAL_NUMBERS_TO_PRINT = 100;int count = 1;int n = 1;while (count <= PENTAGONAL_NUMBERS_TO_PRINT) {int pentagonalNumber = getPentagonalNumber(n);n++;if (count % PENTAGONAL_NUMBERS_PER_LINE == 0)System.out.printf("%-7d\n", pentagonalNumber);elseSystem.out.printf("%-7d", pentagonalNumber);count++;}}public static int getPentagonalNumber(int n) {return n * (3 * n - 1) / 2;}}5_2import java.util.Scanner;public class Exercise02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter an integerSystem.out.print("Enter an interger: ");long number = input.nextLong();System.out.println("The sum of the digits in " + number + " is " + sumDigits(number));}public static int sumDigits(long n) {int sum = 0;long remainingN = n;do {long digit = remainingN % 10;remainingN = remainingN / 10;sum += digit;} while (remainingN != 0);return sum;}}第03题import java.util.Scanner;public class Exercise03 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();//Display resultSystem.out.println("Is " + number + " a palindrome? " + isPalindrome(number));}public static boolean isPalindrome(int number) {if (number == reverse(number))return true;elsereturn false;}public static int reverse(int number) {int reverseNumber = 0;do {int digit = number % 10;number = number / 10;reverseNumber = reverseNumber * 10 + digit;} while (number != 0);return reverseNumber;。
第五章编程题1.编写一个程序,实现字符串大小写的转换并倒序输出。
要求如下:(1)使用for循环将字符串“HelloWorld”从最后一个字符开始遍历。
(2)遍历的当前字符如果是大写字符,就使用toLowerCase()方法将其转换为小写字符,反之则使用toUpperCase()方法将其转换为大写字符。
(3)定义一个StringBuffer对象,调用append()方法依次添加遍历的字符,最后调用StringBuffer对象的toString()方法,并将得到的结果输出。
【参考答案】public class Chap5e {public static void main(String[] args) {String str="Hell5oWorld";char[] ch=str.toCharArray();StringBuffer s=new StringBuffer();for(int i=ch.length-1;i>=0;i--){if(ch[i]>='A'&&ch[i]<='Z')s.append(String.valueOf(ch[i]).toLowerCase());elseif(ch[i]>='a'&&ch[i]<='z')s.append(String.valueOf(ch[i]).toUpperCase());elses.append(String.valueOf(ch[i]));}System.out.print(s.toString());}}2. 利用Random类来产生5个20`30之间的随机整数并输出。
【参考答案】import java.util.Random;public class Chap5e {public static void main(String[] args) {Random r=new Random();for(int i=0;i<5;i++){System.out.println(r.nextInt(30-20+1)+20);}}}3. 编程. 已知字符串:”this is a test of java”.按要求执行以下操作:(1) 统计该字符串中字母s出现的次数(2) 取出子字符串”test”(3) 将本字符串复制到一个字符数组Char[] str中.(4) 将字符串中每个单词的第一个字母变成大写,输出到控制台。
第5章习题解答1.使用抽象和封装有哪些好处?答:抽象是人们解决问题的基本手段,程序设计过程中需要对问题领域进行分析、设计中得出的抽象概念,然后封装成一些类。
封装也称为信息隐藏,是指利用抽象数据类型将数据和基于数据的操作封装在一起,使其构成一个不可分割的独立实体,数据被保护在抽象数据类型的内部,尽可能地隐藏内部的细节,只保留一些对外接口使之与外部发生联系。
系统的其他部分只有通过包裹在数据外面的被授权的操作来与这个抽象数据类型交流与交互。
也就是说,用户无需知道对象内部方法的实现细节,但可以根据对象提供的外部接口(对象名和参数)访问该对象。
把对象中相同或相似地地方抽象出来,从特殊到一半,从具体到抽象的过程,对象经过抽象得到类,类的实例化成了对象。
也可以高度抽象成接口,让不完全相同,但包含相同点的对象实现此接口,也就是利用多态实现。
把相同点抽象出来,抽象成此类或接口的方法、属性、字段等,封装就是隐藏某个对象的与其基本特性没有很大关系的所有详细信息的过程,就是将需要让其他类知道的暴露出来,不需要让其他类了解的全部隐藏起来,封装可以阻止对不需要信息的访问,我们可以使用访问指定符实现封装,也可以使用方法实现封装,可以将隐藏的信息作为参数或者属性值、字段指传给公共的接口或方法,以实现隐藏起来的信息和公开信息的交互。
封装的目的就是为了实现“高内聚,低耦合”。
高内聚就是类的内部数据操作细节自己完成,不允许外部干涉,就是这个类只完成自己的功能,不需要外部参与;低耦合,就是仅暴露很少的方法给外部使用。
2.构造方法的作用是什么?它与一般的成员方法在使用和定义方面有什么区别?答:构造方法用于生成一个对象实例,并对对象实例中的成员变量初始化。
当用new创建一个类的新的对象时,构造方法立即执行。
构造方法名字必须与类名相同。
3.Overload和Override的区别?答:方法重载(overloading)与方法覆盖(overriding)是实现多态性的基本手段,但两者的机制不同。
习题六一、问答题1. 接口中能声明变量吗?不能,接口中只能定义抽象方法和常量2. 接口中能定义非抽象方法吗?不能3. 接口中的常量可以不指定初值吗?不能4.什么叫接口的回调?用实现接口的类创建对象,赋值给该接口声明的接口变量5.可以在接口中只声明常量,不声明抽象方法吗?可以6. 内部类的外嵌类的成员变量在内部类中有效吗?有效7. 内部类中的方法可以调用外嵌类中的方法吗?内部类可以访问外部类的成员,包括private成员。
外部类虽然不能直接访问内部类的成员, 但是可以通过内部类的实例访问内部类的成员。
8. 内部类的类体中可以声明类变量和类方法吗?静态内部类可以定义静态成员,非静态内部类不能定义静态成员。
9. 匿名类一定是内部类吗?一定二、选择题1.下列哪个叙述是正确的 DA. 一个类最多可以实现两个接口。
//一个类可以实现(implements)多个接口,就是Java中多继承现象。
B.如果一个抽象类实现某个接口,那么它必须要重写接口中的全部方法。
C.如果一个非抽象类实现某个接口,那么它可以只重写接口中的部分方法。
//实现某个接口的类如果不是抽象类,则该类必须实现接口中的所有抽象方法。
D.允许接口中只有一个抽象方法。
2.下列哪一个叙述是正确的? CA.和接口有关的匿名类可以是抽象类。
//匿名内部类不能是抽象类。
因为在创建匿名内部类的时候,会立即创建匿名内部类的对象。
B.和类有关的匿名类还可以额外地实现某个指定的接口。
C.和类有关的匿名类一定是该类的一个非抽象子类。
D.和接口有关的匿名类的类体中可以有static成员变量。
//匿名类是一个内部类,类体不可声明static成员变量和static方法3.下列接口中标注的(A,B,C,D)中,哪两个是错误的? ABinterface Takecare {protected void speakHello(); //A 接口中的方法都是public,不能是protectedpublic abstract static void cry(); //B 接口中的方法不能用static修饰int f(); //Cabstract float g(); //D}4.将下列(A,B,C,D)哪个代码替换下列程序中的【代码】不会导致编译错误。