java考试题库第五章
【免费下载】java答案第五章

5.声明一个具有内部类的类,此内部类只有一个非默认的构造方法;声明另外一个具有内 部类的类,此内部类继承第一个内部类。
//A 类 class A{
class ClassOfA{ public ClassOfA(){
} } } //B 类 public class B{ class ClassOfB extends A.ClassOfA{ public ClassOfB(A b){
}
运行结果:
对全部高中资料试卷电气设备,在安装过程中以及安装结束后进行高中资料试卷调整试验;通电检查所有设备高中资料电试力卷保相护互装作置用调与试相技互术关,系电,力根通保据过护生管高产线中工敷资艺设料高技试中术卷资,配料不置试仅技卷可术要以是求解指,决机对吊组电顶在气层进设配行备置继进不电行规保空范护载高与中带资负料荷试下卷高问总中题体资,配料而置试且时卷可,调保需控障要试各在验类最;管大对路限设习度备题内进到来行位确调。保整在机使管组其路高在敷中正设资常过料工程试况中卷下,安与要全过加,度强并工看且作护尽下关可都于能可管地以路缩正高小常中故工资障作料高;试中对卷资于连料继接试电管卷保口破护处坏进理范行高围整中,核资或对料者定试对值卷某,弯些审扁异核度常与固高校定中对盒资图位料纸置试,.卷保编工护写况层复进防杂行腐设自跨备动接与处地装理线置,弯高尤曲中其半资要径料避标试免高卷错等调误,试高要方中求案资技,料术编试交写5、卷底重电保。要气护管设设装线备备置敷4高、调动设中电试作技资气高,术料课中并3中试、件资且包卷管中料拒含试路调试绝线验敷试卷动槽方设技作、案技术,管以术来架及避等系免多统不项启必方动要式方高,案中为;资解对料决整试高套卷中启突语动然文过停电程机气中。课高因件中此中资,管料电壁试力薄卷高、电中接气资口设料不备试严进卷等行保问调护题试装,工置合作调理并试利且技用进术管行,线过要敷关求设运电技行力术高保。中护线资装缆料置敷试做设卷到原技准则术确:指灵在导活分。。线对对盒于于处调差,试动当过保不程护同中装电高置压中高回资中路料资交试料叉卷试时技卷,术调应问试采题技用,术金作是属为指隔调发板试电进人机行员一隔,变开需压处要器理在组;事在同前发一掌生线握内槽图部内 纸故,资障强料时电、,回设需路备要须制进同造行时厂外切家部断出电习具源题高高电中中源资资,料料线试试缆卷卷敷试切设验除完报从毕告而,与采要相用进关高行技中检术资查资料和料试检,卷测并主处且要理了保。解护现装场置设。备高中资料试卷布置情况与有关高中资料试卷电气系统接线等情况,然后根据规范与规程规定,制定设备调试高中资料试卷方案。
Java程序设计 第五章 测验答案 慕课答案 UOOC优课 深圳大学继续教育学院

第5章测验-5.1String类一、单选题 (共100.00分)1.编译及运行以下代码,下列选项哪个是正确的String s=new String("Bicycle");int iBegin=1;char iEnd=3;System.out.println(s.substring(iBegin,iEnd));A.输出BicB.输出icC.输出icyD.编译错误正确答案:B2.下面哪个是对字符串String的正确定义A.String s1=null;B.String s2='null';C.String s3=(String)'abc';D.String s4=(String)'\uface';正确答案:A3.字符串s=”Java”,找出字母v在字符串s中的位置,以下哪个选项是正确的A.mid(2,s);B.charAt(2);C.indexOf(s);D.s.indexOf('v');正确答案:D4.给出以下变量定义,以下哪个语句是正确的 String s1=new String("Hello");String s2=new String("there");String s3=new String();A.s3=s1 + s2;B.s3=s1 - s2;C.s3=s1 & s2;D.s3=s1 && s2;正确答案:A5.以下哪个方法可以返回字符串的长度:A.length()pareto()C.indexof()D.touppercase()正确答案:A。
《Java程序设计》教材第五章练习题答案

习题一、选择题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初始值,再为该类定义加、减、乘、除等公有方法,分别对两个成员变量执行加减乘除的运算。
java复习题库第五、六章

第五章多线程选择题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程序的并发机制,它能同步共享数据、处理不同的事件。
《Java语言程序设计-基础篇》答案-第05章

第5章 数组
复习题
5.1 答:(略)
5.2 答:使用数组名和下标。
如:arrayName[index]
5.3 答:声明数组时不为数组分配内存,使用new运算符为数组分配内存。
输出结果:
x is 60
The size of numbers is 30
5.4 答:依次为:对、错、对、错
5.5 答:有效的数组名分别是:d, f, r
5.6 答:整数,0
5.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 3
5.14 答:数组存放在堆(heap)中。
第2问参见P144图5-7。
5.15 - 5.18 (略)
5.19 答:int[] matrix = new int[4][5];
5.20 答:可以。
5.21 答:输出:array[0][1] is 2。
《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。
Java课后题-第5章答案

一.程序设计题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类型),并且所有属性为私有。
JAVA语言程序设计(第8版)第5章完整答案programming-exercises(程序练习题)答案完整版

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;。
Java基础第5章编程题答案

第五章编程题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) 将字符串中每个单词的第一个字母变成大写,输出到控制台。
Java第五章作业答案

习题六一、问答题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)哪个代码替换下列程序中的【代码】不会导致编译错误。
JAVA语言程序的设计第8版第5章完整答案programmingexercises程序练习题答案完整版

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;}}第04题import java.util.Scanner;public class Exercise04 {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.print("The reversal of " + number + " is ");reverse(number);}public static void reverse(int number) {int reverseNumber = 0;do {int digit = number % 10;number = number / 10;reverseNumber = reverseNumber * 10 + digit;} while (number != 0);System.out.println(reverseNumber);}}第05题import java.util.Scanner;public class Exercise05 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter three numbersSystem.out.print("Enter three numbers: ");double num1 = input.nextDouble();double num2 = input.nextDouble();double num3 = input.nextDouble();System.out.print(num1 + " " + num2 + " " + num3 + " in increasing order: ");displaySortedNumbers(num1, num2, num3);}public static void displaySortedNumbers(double num1, double num2, double num3) {double max = Math.max(Math.max(num1, num2), num3);double min = Math.min(Math.min(num1, num2), num3);double second = 0;if (num1 != max && num1 != min)second = num1;if (num2 != max && num2 != min)second = num2;if (num3 != max && num3 != min)second = num3;System.out.println(min + " " + second + " " + max);}}5.6import java.util.Scanner;public class Exercise06 {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();displayPattern(number);}public static void displayPattern(int n) {int i;int j;for (i = 1; i <= n; i++) {for (j = 0; j < n - i; j++)System.out.print(" ");for (j = 0; j <= i - 1; j++)System.out.printf("%-5d", i - j);System.out.println();}}}5.7import java.util.Scanner;public class Exercise07 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter investment amountSystem.out.print("Enter the investment amount: ");double investmentAmount = input.nextDouble();//Prompt the user to enter interest rateSystem.out.print("Enter the annual interest rate: ");double annualInterestRate = input.nextDouble();//Prompt the user to enter yearsSystem.out.print("Enter number of years: ");int years = input.nextInt();System.out.println("\nThe amount invested: " + investmentAmount);System.out.println("Annual interest rate: " + annualInterestRate + "%");System.out.println("Years\tFuture Value");for (int i = 1; i <= years; i++) {System.out.print(i + "\t");System.out.printf("%10.2f\n",futureInvestmentValue(investmentAmount, annualInterestRate / 1200, i));}}public static double futureInvestmentValue(double investmentAmount, doublemonthInterestRate, int years) {return investmentAmount * Math.pow(1 + monthInterestRate, years * 12);}}5.8public class Exercise08 {public static void main(String[] args) {System.out.println("Celsius\tFahrenheit\tFahrenheit\tCelsius");for (double celsius = 40, fahrenheit = 120; celsius >= 31 && fahrenheit >= 30; celsius--, fahrenheit -= 10) {System.out.println(celsius + "\t" + (int)(celsiusToFahrenheit(celsius) * 100) / 100.0 + "\t\t" +fahrenheit + "\t\t" + (int)(fahrenheitToCelsius(fahrenheit) * 100) / 100.0);}}public static double celsiusToFahrenheit(double celsius) {return (9.0 / 5) * celsius + 32;}public static double fahrenheitToCelsius(double fahrenheit) {return (fahrenheit - 32) * 5.0 / 9;}}5.9public class Exercise09 {public static void main(String[] args) {System.out.println("Feet\tMeters\tMeters\tFeet");for (double feet = 1, meters = 20; feet <= 10 && meters <= 65; feet++, meters += 5) {System.out.println(feet + "\t" + (int)(footToMeter(feet) * 1000) / 1000.0 + "\t" +meters + "\t" + (int)(meterToFoot(meters) * 1000) / 1000.0);}}public static double footToMeter(double foot) {return foot * 0.305;}public static double meterToFoot(double meter) {return meter / 0.305;}}5.10public class Exercise10 {public static void main(String[] args) {int count = 0;int number = 1;for (number = 1; number < 10000; number++) {if (isPrime(number))count++;}System.out.println("The number of prime numbers less than 10000 is " + count);}public static boolean isPrime(int number) {for (int i = 2; i <= number / 2; i++) {if (number % i == 0)return false;}return true;}}5.11public class Exercise11 {public static void main(String[] args) {System.out.println("Sales Amount\tCommission");for (double salesAmount = 10000.0; salesAmount <= 100000; salesAmount += 5000) {System.out.println(salesAmount + "\t\t" + computeCommission(salesAmount));}}public static double computeCommission(double salesAmount) {if (salesAmount <= 5000)return salesAmount * 0.08;else if (salesAmount <= 10000)return 5000 * 0.08 + (salesAmount - 5000) * 0.10;elsereturn 5000 * 0.08 + (10000 - 5000) * 0.10 + (salesAmount - 10000) * 0.12;}}5.12public class Exercise12 {public static void main(String[] args) {char ch1 = '1';char ch2 = 'Z';int number = 10;printChars(ch1, ch2, number);}public static void printChars(char ch1, char ch2, int numberPerLine) { int count = 1;for (char i = ch1; i <= ch2; i++) {if (count % numberPerLine == 0)System.out.println(i);elseSystem.out.print(i + " ");count++;}}}5.13public class Exercise13 {public static void main(String[] args) {System.out.println("i\tm(i)");for (int i = 1; i <= 50; i++) {System.out.print(i + "\t");System.out.printf("%-10.4f\n", m(i));}}public static double m(int n) {double sum = 0;for (double i = n; i >= 1; i--)sum += i / (i + 1);return sum;}}5.14public class Exercise14 {public static void main(String[] args) {System.out.println("i\tm(i)");for (int i = 10; i <= 100; i += 10) {System.out.print(i + "\t");System.out.printf("%-10.5f\n", m(i));}}public static double m(int n) {double sum = 0;for (double i = n; i >= 0; i -= 2) {sum += 4 * (1 / (2 * i + 1) - 1 / (2 * (i + 1) + 1));}return sum;}}5.15public class Exercise15 {public static void main(String[] args) {System.out.println("Taxble Single Married Married Head of");System.out.println("Income Joint Separate a House");int taxableIncome;int status;for (taxableIncome = 50000; taxableIncome <= 60000; taxableIncome += 50) {System.out.printf("%-5d", taxableIncome);System.out.print(" ");for (status = 0; status <= 3; status++) {System.out.printf("%-5d", (int)computetax(status, taxableIncome));System.out.print(" ");}System.out.println();}}public static double computetax(int status, double taxableIncome) { double tax = 0;double income = taxableIncome;if (status == 0) {if (income <= 8350)tax = income * 0.10;else if (income <= 33950)tax = 8350 * 0.10 + (income - 8350) * 0.15;else if (income <= 82250)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;else if (income <= 171550)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;else if (income <= 372950)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.33;elsetax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;}else if (status == 1) {if (income <= 16700)tax = income * 0.10;else if (income <= 67900)tax = 16700 * 0.10 + (income - 16700) * 0.15;else if (income <= 137050)tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25;else if (income <= 208850)tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;else if (income <= 372950)tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (income - 208850) * 0.33;elsetax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (372950 - 208850) * 0.33 + (income - 372950) * 0.35;}else if (status == 2) {if (income <= 8350)tax = income * 0.10;else if (income <= 33950)tax = 8350 * 0.10 + (income - 8350) * 0.15;else if (income <= 68525)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;else if (income <= 104425)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (income - 68525) * 0.28;else if (income <= 186475)tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (income - 104425) * 0.33;elsetax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186475 - 104425) * 0.33 + (income - 186475) * 0.35;}else if (status == 3) {if (income <= 11950)tax = income * 0.10;else if (income <= 45500)tax = 11950 * 0.10 + (income - 11950) * 0.15;else if (income <= 117450)tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25;else if (income <= 190200)tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (income - 117450) * 0.28;else if (income <= 372950)tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (income - 190200) * 0.33;elsetax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33 + (income - 372950) *0.35;}return tax;}}5.16public class Exercise16 {public static void main(String[] args) {for (int year = 2000; year <= 2010; year++) {System.out.println("Year " + year + " has " + numberOfDaysInAYear(year) + " days.");}}public static int numberOfDaysInAYear(int year) {if (isLeapYear(year))return 366;elsereturn 365;}public static boolean isLeapYear(int year) {boolean isLeapYear = false;if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)isLeapYear = true;return isLeapYear;}}5.17import java.util.Scanner;public class Exercise17 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter an integer number: ");int n = input.nextInt();printMatrix(n);}public static void printMatrix(int n) {for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++)System.out.print((int)(Math.random() * 2) + " ");System.out.println();}}}5.18public class Exercise18 {public static void main(String[] args) {System.out.println("Number\tSquareRoot");for (int i = 0; i <= 20; i += 2) {System.out.print(i + "\t ");System.out.printf("%6.4f\n", squareRoot(i));}}public static double squareRoot(int n) {return Math.sqrt(n);}}5.19import java.util.Scanner;public class Exercise19 {/*** main method*/public static void main(String[] args) {//Create a ScannerScanner input = new Scanner(System.in);//Prompt the user to enter three sides for a triangleSystem.out.print("Enter three sides for a triangle: ");double side1 = input.nextDouble();double side2 = input.nextDouble();double side3 = input.nextDouble();if (isValid(side1, side2, side3))System.out.println("The area of the triangle is " + area(side1, side2, side3));elseSystem.out.println("The input is invalid!");}/*** Returns true if the sum of any two sides is greater than the third side */public static boolean isValid(double side1, double side2, double side3) { boolean isValid = false;if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) isValid = true;return isValid;}/*** Returns the area of the triangle*/public static double area(double side1, double side2, double side3) { double s = (side1 + side2 + side3) / 2;double area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));return area;}}5.20public class Exercise20 {public static void main(String[] args) {System.out.println("Degree \tSin \tCos");for (int degree = 0; degree <= 360; degree = degree + 10) {System.out.print(degree + "\t ");System.out.printf("%6.4f\t ", sin(Math.toRadians(degree)));System.out.printf("%6.4f\n", cos(Math.toRadians(degree)));}}public static double sin(double radians) {return Math.sin(radians);}public static double cos(double radians) {return Math.cos(radians);}}5.21import java.util.Scanner;public class Exercise21 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter ten numbersSystem.out.print("Enter ten numbers: ");double n0 = input.nextDouble();double n1 = input.nextDouble();double n2 = input.nextDouble();double n3 = input.nextDouble();double n4 = input.nextDouble();double n5 = input.nextDouble();double n6 = input.nextDouble();double n7 = input.nextDouble();double n8 = input.nextDouble();double n9 = input.nextDouble();System.out.println("The mean is " + computeMean(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9));System.out.println("The standard deviation is " + standardDeviation(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9));}public static double computeMean(double n0, double n1, double n2, double n3, double n4, double n5, double n6, double n7, double n8, double n9) {return (n0 + n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9) / 10;}public static double standardDeviation(double n0, double n1, double n2, double n3, double n4, double n5, double n6, double n7, double n8, double n9) { double i = n0 * n0 + n1 * n1 + n2 * n2 + n3 * n3 + n4 * n4 + n5 * n5 + n6 * n6 + n7 * n7 + n8 * n8 + n9 * n9;double j = (n0 + n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9) * (n0 + n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9);return Math.sqrt((i - j / 10) / (10 - 1));}}5.22import java.util.Scanner;public class Exercise22 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a number: ");double num = input.nextDouble();System.out.println("The approximate square root of " + num + " is " + approximateSquareRoot(num));}public static double approximateSquareRoot(double n) {double lastGuess = 1;double nextGuess = (lastGuess + (n / lastGuess)) / 2;while (Math.abs(nextGuess - lastGuess) > 0.0001) {lastGuess = nextGuess;nextGuess = (lastGuess + (n / lastGuess)) / 2;}return nextGuess;}}5.23public class Exercise23 {public static void main(String[] args) {final int NUMBERS_PER_LINE = 10;int count = 1;for (int i = 0; i < 100; i++) {if (count % NUMBERS_PER_LINE != 0)System.out.print(.jackfangqi.chapter05.examples.RandomCharacter.getRandomUp perCaseLetter() + " ");if (count % NUMBERS_PER_LINE == 0)System.out.println(.jackfangqi.chapter05.examples.RandomCharacter.getRandom UpperCaseLetter());count++;}count = 1;for (int i = 0; i < 100; i++) {if (count % NUMBERS_PER_LINE != 0)System.out.print(.jackfangqi.chapter05.examples.RandomCharacter.getRandomDi gitCharacter() + " ");if (count % NUMBERS_PER_LINE == 0)System.out.println(.jackfangqi.chapter05.examples.RandomCharacter.getRandom DigitCharacter());count++;}}}5.24public class Exercise24 {public static void main(String[] args) {showCurrentDate();showCurrentTime();}public static void showCurrentDate() {System.out.println("Current date is " + getMonthName() + " " + getCurrentDay() + ", " + getCurrentYear());}public static long totalNumberOfDays() {//Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();long totalSeconds = totalMilliseconds / 1000;long totalMinutes = totalSeconds / 60;long totalHours = totalMinutes / 60;long totalDays = totalHours / 24;return totalDays;}public static int getCurrentYear() {long n = 0;int year = 1970;while (n <= totalNumberOfDays()) {if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))n += 366;elsen += 365;year++;}return year - 1;}public static long getRemainingDays() {long m = 0;for (int i = 1970; i < getCurrentYear(); i++) {if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0))m += 366;elsem += 365;}return totalNumberOfDays() - m;}public static int getCurrentMonth() {int j = 0;int i = 0;while (j <= getRemainingDays()) {i++;if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)j += 31;if (i == 4 || i == 6 || i == 9 || i == 11)j += 30;if (i == 2) {if (getCurrentYear() % 400 == 0 || (getCurrentYear() % 4 == 0 && getCurrentYear() % 100 != 0))j += 29;elsej += 28;}}return i;}public static String getMonthName() {String monthName = "";switch (getCurrentMonth()) {case 1: monthName = "January";break;case 2: monthName = "February";break;case 3: monthName = "March";break;case 4: monthName = "April";break;case 5: monthName = "May";break;case 6: monthName = "June";break;case 7: monthName = "July";break;case 8: monthName = "August";break;case 9: monthName = "September";break;case 10: monthName = "October";break;case 11: monthName = "November";break;case 12: monthName = "December";}return monthName;}public static long getCurrentDay() {int j = 0;for (int i = 1; i < getCurrentMonth(); i++) {if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)j += 31;if (i == 4 || i == 6 || i == 9 || i == 11)j += 30;if (i == 2) {if (getCurrentYear() % 400 == 0 || (getCurrentYear() % 4 == 0 && getCurrentYear() % 100 != 0))j += 29;elsej += 28;}}return getRemainingDays() - j + 1;}public static void showCurrentTime() {//Obtain the total milliseconds since midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();//Obtain the total seconds since midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;//Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;//Obtain the total minuteslong totalMinutes = totalSeconds / 60;//Compute the current minute in the hourlong currentMinute = totalMinutes % 60;//Obtain the total hourlong totalHours = totalMinutes / 60;//Compute the current hourlong currentHour = totalHours % 24 + 8;System.out.println("Current time is "+currentHour+":"+currentMinute+":"+currentSecond+" (GMT+8)");}}5.25import java.util.Scanner;public class Exercise25 {public static void main(String[] args) {Scanner input = new Scanner(System.in);//Prompt the user to enter millisecondsSystem.out.print("Enter milliseconds: ");long milliseconds = input.nextLong();System.out.print(milliseconds + " is " + convertMillis(milliseconds));}public static String convertMillis(long millis) {//Obtain the total secondslong totalSeconds = millis / 1000;//Compute the remaining secondslong remainingSeconds = totalSeconds % 60;//Obtain the total minuteslong totalMinutes = totalSeconds / 60;//Compute the remaining minuteslong remainingMinutes = totalMinutes % 60;//Obtain the total hourslong totalHours = totalMinutes / 60;return totalHours + ":" + remainingMinutes + ":" + remainingSeconds;}}5.26public class Exercise26 {public static void main(String[] args) { int countOfPalindromicPrimes = 0;int count = 1;int i = 2;while (countOfPalindromicPrimes < 100) { if (isPrime(i) && isPalindrome(i)) {if (count % 10 != 0)System.out.printf("%6d ", i);elseSystem.out.printf("%6d\n", i);count++;countOfPalindromicPrimes++;}i++;}}public static boolean isPrime(int m) {boolean isPrime = true;for (int j = 2; j <= m / 2; j++) {if (m % j == 0) {isPrime = false;break;}}return isPrime;}public static boolean isPalindrome(int n) { if (n == reverse(n))return true;elsereturn false;}public static int reverse(int n) {int reverseNumber = 0;do {int digit = n % 10;n = n / 10;reverseNumber = reverseNumber * 10 + digit;} while (n != 0);return reverseNumber;}}5.27public class Exercise27 {public static void main(String[] args) {int countOfEmirps = 0;int countOfEmirpsPerLine = 1;int i = 2;while (countOfEmirps < 100) {if (isPrime(i) && isNonpalindrome(i) && isPrime(reverse(i))) { if (countOfEmirpsPerLine % 10 != 0)System.out.printf("%4d ", i);elseSystem.out.printf("%4d\n", i);countOfEmirps++;countOfEmirpsPerLine++;}i++;}}public static boolean isPrime(int n) {boolean isPrime = true;for (int i = 2; i <= n /2; i++) {if (n % i == 0) {isPrime = false;break;}}return isPrime;}public static boolean isNonpalindrome(int n) {if (n == reverse(n))return false;elsereturn true;}public static int reverse(int n) {int reversal = 0;do {int digit = n % 10;n = n / 10;reversal = reversal * 10 + digit;} while (n != 0);return reversal;}}5.28public class Exercise28 {public static void main(String[] args) {System.out.println("p\t2^p - 1");for (int p = 2; p <= 31; p++) {if (isPrime(Math.pow(2, p) - 1))System.out.println(p + "\t" + (Math.pow(2, p) - 1));}}public static boolean isPrime(double n) {boolean isPrime = true;for (int i = 2; i <= n /2; i++) {if (n % i == 0) {isPrime = false;break;}}return isPrime;}}5.29public class Exercise29 {public static void main(String[] args) {//Generate two random numbers between 1 and 6int i = (int)(Math.random() * 6 + 1);int j = (int)(Math.random() * 6 + 1);if (isCraps(i, j))System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou lose");if (isNatural(i, j))System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou win");if (isPoint(i, j))point(i, j);}public static int sum(int n, int m) {return n + m;}public static boolean isCraps(int i, int j) {boolean isCraps = false;if (sum(i, j) == 2 || sum(i, j) == 3 || sum(i, j) == 12)isCraps = true;return isCraps;}public static boolean isNatural(int i, int j) {boolean isNatural = false;if (sum(i, j) == 7 || sum(i, j) == 11)isNatural = true;return isNatural;}public static boolean isPoint(int i, int j) {boolean isPoint = false;if (!isCraps(i, j) && !isNatural(i, j))isPoint = true;return isPoint;}public static void point(int i, int j) {int point = sum(i, j);System.out.println("You rolled " + i + " + " + j + " = " + point + "\npoint is " + point);//Generate two random numbers between 1 and 6i = (int)(Math.random() * 6 + 1);j = (int)(Math.random() * 6 + 1);if (sum(i, j) == 7)System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou lose");if (sum(i, j) == point)System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j) + "\nYou win");while (sum(i, j) != 7 && sum(i, j) != point) {i = (int)(Math.random() * 6 + 1);j = (int)(Math.random() * 6 + 1);System.out.println("You rolled " + i + " + " + j + " = " + sum(i, j));if (sum(i, j) == 7)System.out.println("You lose");if (sum(i, j) == point)System.out.println("You win");}}}5.30public class Exercise30 {public static void main(String[] args) {for (int i = 2; i < 1000; i++) {if (isPrime(i) && isPrime(i + 2))System.out.println("(" + i + ", " + (i + 2) + ")");}}。
JAVA期末复习题及答案——第五章

JAVA期末复习题及答案——第五章一.填空题1.Java不直接支持多继承,但可以通过接口实现多继承。
2.任何一个Java程序都默认引入了一个包,这个包的名字叫做java. lang 。
使用已经存在的类定义作为基础建立新的类定义,这样的技术叫做_类的继承__3.用来实现接口的关键字是 implements 。
4. 对象替换原则是指父类的句柄可以指向子类的对象。
5.子类继承父类使用关键字extends6.一个类中如果存在一个或多个抽象方法,那么这个类是一个抽象类。
7.抽象类中可以(“可以”或者“不可以”)不存在抽象的方法,可以(“可以”或者“不可以”)存在非抽象的方法。
8.接口中的属性的默认修饰符为 public static final ,接口中方法的默认修饰符为 public abstract 。
二.选择题1.用来引入已定义好的类或包的语句是:BA、mainB、importC、public classD、class2.下列叙述中,错误的是: DA、父类不能替代子类B、子类能够替代父类C、子类继承父类D、父类包含子类3.程序执行的结果(C)public class Test {String name="Tom";public Test(String name){name=name;}public static void main(String [] args){Test t = new Test("Jack");System.out.println();}}A 编译有错B JackC TomD 以上答案都不对4.在 Java 中,关于static关键字的说法错误的是(D)A static 可以修饰方法B static 可以修饰变量C static 可以修饰代码块D static 修饰的方法,在该方法内部可以访问非静态的类成员变量5.关于 Java 中继承的特点,下列说法正确的是(B)A 使类的定义复杂化B Java 只支持单继承,不可多继承,但可以通过实现接口来达到多继承的目的C 子类继承父类的所有成员变量和方法,包括父类的构造方法D 不可以多层继承,即一个类不可以继承另一个类的子类6.程序的执行结果是(D)public class Test {public static void main(String [] args){Child c = new Child();}}class Father{public Father(){System.out.println("父类无参构造函数");}public Father(String name){System.out.println("父类有参构造函数");}}class Child extends Father{public Child(){this("dd");System.out.println("子类无参构造函数");}public Child(String name){super("dd");System.out.println("子类有参构造函数");}}A 子类无参构造函数子类有参构造函数父类无参构造函数B 子类有参构造函数子类无参构造函数父类无参构造函数C 父类无参构造函数子类有参构造函数子类无参构造函数D 父类有参构造函数子类有参构造函数子类无参构造函数三.判断题1.在进行类的继承时,一个子类只能有一个父类,一个父类也只能有一个子类。
java第五章习题及答案

1.Internet/Intranet Server(服务器),客户端
2.初始化、启动、停止、退出
3.事件
4.ActionEvent,ActionListener,actionPerformed(ActionEvent e)
5.CheckboxGroup,Checkbox,Choice,List,ItemEvent
result.setText(j.toString(i));
}
catch(ArithmeticException ee){
result.setText("divided by zero");
}
}
}
class clearL implements ActionListener{
public void actionPerformed(ActionEvent e){
TextField result=new TextField(10);
Label la1=new Label("first data:");
Label la2=new Label("second data:");
Label la3=new Label("equal:");
Button plus=new Button("+");
二.选择题:
4.b5.A6.A7.a
二.编程题:
1.
importjava.applet.*;
importjava.awt.*;
importjava.awt.event.*;
publicclassExampleextendsAppletimplementsActionListener{
java题库第5章

一、选择题1. Java语言的类间的继承关系是( )。
A) 多重的B) 单重的C) 线程的D) 不能继承2. 以下关于Java语言继承的说法正确的是( )。
A)Java中的类可以有多个直接父类B)抽象类不能有子类C)Java中的接口支持多继承D)最终类可以作为其它类的父类3. 现有两个类A、B,以下描述中表示B继承自A的是( )。
A) class A extends B B) class B implements AC) class A implements B D) class B extends A4. 下列选项中,用于定义接口的关键字是( )。
A)interface B) implements C) abstract D) class5. 下列选项中,用于实现接口的关键字是( B)。
A)interface B) implements C) abstract D) class二、填空题1. 如果子类中的某个变量的变量名与它的父类中的某个变量完全一样,则称子类中的这个变量________了父类的同名变量。
2. 属性的隐藏是指子类重新定义从父类继承来的__________。
3. 如果子类中的某个方法的名字、返回值类型和________与它的父类中的某个方法完全一样,则称子类中的这个方法覆盖了父类的同名方法。
4. Java 仅支持类间的____重继承。
5. 抽象方法只有方法头,没有________。
6. Java 语言的接口是特殊的类,其中包含______常量和_______方法。
三、程序阅读题1.现有类说明如下,请回答问题:public class A{String str1=" Hello! ";String str2=" How are you? ";public String toString( ){ return str1+str2; }}public class B extends A{String str1=" ,Bill.";public String toString( ){ return super.str1+str1; }}问题:1)类A和类B是什么关系?2)类A和类B都定义了str1属性和方法toString( ),这种现象分别称为什么?3)若a是类A的对象,则a.toString( )的返回值是什么?4)若b是类B的对象,则b.toString( )的返回值是什么?2.现有一个类定义如下,请回答问题:class Employee{String name;int age;double wage;static int No=0;Employee(String a1,int a2,double a3){name=a1; age=a2; wage=a3;No++;}}在使用该类时,已使用下面语句生成了该类的对象:Employee e1,e2;e1=new Employee("王劲",26,6300);e2=new Employee("张山",30,3800);问题:1),e2.age,e2.wage的值各是什么2)生成对象e1、e2后,e1.No值为多少?能否通过类名做前缀引用属性No?3.阅读程序,回答问题。
2023年JAVA语言程序设计期末考试试题及答案应考必备题库五

《JA V A语言程序设计》期末考试试题及答案5(应考必备题库)一、单项选择题1.当某一线程正处在休眠状态, 而另一种线程用 Thread 类中旳 interrupt() 措施中断它时, 抛出旳异常类型是()。
A) IOException B) RuntimeExceptionC) InterruptedException D) ClassNotFoundException2.下面旳程序段旳功能是( )。
File file1=new File("d:\\xxx\\yyy\\zzz");file1.mkdirs();A)在目前目录下生成子目录: \xxx\yyy\zzz B)生成目录: e:\xxx\yyy\zzzC)在目前目录下生成文献xxx.yyy.zzz D)以上说法都不对3.应用程序旳main措施中有如下语句, 则输出旳成果是 ( )。
String s = "xxxxxxxxxxxxxxx#123#456#zzzzz";int n = s.indexOf("#");int k = s.indexOf("#", n+1);String s2 = s.substring(n+1, k);System.out.println(s2);A) 123456 B) 123 C) xxxxxxxxxxxxxxx D) zzzzz4.有关下面旳程序Test.java说法对旳旳是( )。
public class Test {String x="1";int y;public static void main(String args[]) {int z=2;System.out.println(x+y+z);}}A)3 B)102 C) 12 D)程序有编译错误5.应用程序旳main措施中有如下语句, 则输出旳成果是 ( )。
java习题及答案第5章习题参考答案

java习题及答案第5章习题参考答案第5章习题解答1.使⽤抽象和封装有哪些好处?答:抽象是⼈们解决问题的基本⼿段,程序设计过程中需要对问题领域进⾏分析、设计中得出的抽象概念,然后封装成⼀些类。
封装也称为信息隐藏,是指利⽤抽象数据类型将数据和基于数据的操作封装在⼀起,使其构成⼀个不可分割的独⽴实体,数据被保护在抽象数据类型的内部,尽可能地隐藏内部的细节,只保留⼀些对外接⼝使之与外部发⽣联系。
系统的其他部分只有通过包裹在数据外⾯的被授权的操作来与这个抽象数据类型交流与交互。
也就是说,⽤户⽆需知道对象内部⽅法的实现细节,但可以根据对象提供的外部接⼝(对象名和参数)访问该对象。
把对象中相同或相似地地⽅抽象出来,从特殊到⼀半,从具体到抽象的过程,对象经过抽象得到类,类的实例化成了对象。
也可以⾼度抽象成接⼝,让不完全相同,但包含相同点的对象实现此接⼝,也就是利⽤多态实现。
把相同点抽象出来,抽象成此类或接⼝的⽅法、属性、字段等,封装就是隐藏某个对象的与其基本特性没有很⼤关系的所有详细信息的过程,就是将需要让其他类知道的暴露出来,不需要让其他类了解的全部隐藏起来,封装可以阻⽌对不需要信息的访问,我们可以使⽤访问指定符实现封装,也可以使⽤⽅法实现封装,可以将隐藏的信息作为参数或者属性值、字段指传给公共的接⼝或⽅法,以实现隐藏起来的信息和公开信息的交互。
封装的⽬的就是为了实现“⾼内聚,低耦合”。
⾼内聚就是类的内部数据操作细节⾃⼰完成,不允许外部⼲涉,就是这个类只完成⾃⼰的功能,不需要外部参与;低耦合,就是仅暴露很少的⽅法给外部使⽤。
2.构造⽅法的作⽤是什么?它与⼀般的成员⽅法在使⽤和定义⽅⾯有什么区别?答:构造⽅法⽤于⽣成⼀个对象实例,并对对象实例中的成员变量初始化。
当⽤new创建⼀个类的新的对象时,构造⽅法⽴即执⾏。
构造⽅法名字必须与类名相同。
3.Overload和Override的区别?答:⽅法重载(overloading)与⽅法覆盖(overriding)是实现多态性的基本⼿段,但两者的机制不同。
java程序设计项目教程第五章答案

参考答案:
1.A 2.A3.C 4.B5.B6.B7.A8.B9.A10.C
二、填空题
参考答案:
1.swing2.布局管理器3.setLayout()4.mouseRelease
5.适配器6.ActionListener7.事件事件源8.JMenu
三、编程
1.设计如图样式的图形用户界面(不要求实现功能)。
JTextField t2=newJTextField("57",3);
JTextField t3=newJTextField("59",3);
JTextField t4=newJTextField(3);
JTextField t5=newJTextField(3);
JTextField t6=newJTextField(3);
JButton answerButton;
JButton questionButton;
JButton scoreButton;
public TestPanel()
{
setLayout(new BorderLayout());
JPanel northPanel=new JPanel();
northPanel.setLayout(new GridLayout(2,1));
JLabel b5 = newJLabel("闹钟时间:");
JLabel b6 = newJLabel("时");
JLabel b7= newJLabel("分");
JLabel b8 = newJLabel("秒");
JLabel b9 = newJLabel("闹钟设置");
Java面向对象程序设计案例教程(王贺) 第五章习题答案[4页]
![Java面向对象程序设计案例教程(王贺) 第五章习题答案[4页]](https://img.taocdn.com/s3/m/a3b02cdc760bf78a6529647d27284b73f24236ea.png)
5.7 习题1. 选择题1)下列不属于面向对象编程的3个特征的是(B)A.封装B. 指针操作C. 多态D. 继承2)下列关于继承性的描述中,错误的是(C)A.一个类可以同时生成多个子类B.子类继承父类除了private修饰之外的所有成员C.Java语言支持单重继承和多重继承D.Java语言通过接口实现多重继承3)下列对于多态的描述中,错误的是(A)A.Java语言允许运算符重载B.Java语言允许方法符重载C.Java语言允许成员变量覆盖D.多态性提高了程序的抽象性和简洁性4)关键字super的作用是(D)A.用来访问父类被隐藏的成员变量B.用来调用父类中被重载的方法C.用来调用父类的构造方法D.以上都是5)下面程序定义了一个类,关于该类,说法正确的是(D)abstract class Aa{…}A.该类能调用Aa()构造方法实例化一个对象B.该类不能被继承C.该类的方法都不能被重载D.以上说法都不对6)下列关于接口的描述中,错误的是(D)A.接口实际上是由常量和抽象方法构成的特殊类B.一个类只允许继承一个接口C.定义接口使用的关键字是interfaceD.在继承接口的类中通常要给出接口中定义的抽象方法的具体实现7)下面关于包的描述中,错误的是(A)A.包是若干对象的集合B. 使用package语句创建包C. 使用import语句引入包D. 包分为有名包和无名包两种8)如果java.abc.def中包含xyz类,则该类可记作(C)A. java.xyzB. java.abc.xyzC. java.abc.def.xyzD. java.xyz.abc9)下列方法中,与方法public void add(int a){}为不合理的重载方法的是( B)A. public void add(char a)B. public int add(int a)C. public void add(int a, int b)D. public void add(float a)10)设有如下类的定义:public class parent{int change( ) {}}Class Child extends Parent{ }则下面的方法可加入Child类中的是(A)A. public int change( ){ }B. final int change(int i){ }C. private int change( ){ }D. abstract int change( ){ }2.填空题(1) 在Java程序中,把关键字(super)加到方法名称的前面,可实现子类调用父类的方法。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
5-1 下列关于容器的描述中,错误的是DA.容器是由若干个组建和容器组成的B.容器是对图形界面中界面元素的一种管理C.容器是一种对指定宽和高的矩形范围D.容器都是可以独立的窗口5-2 下列界面元素中,不是容器的是AA.ListB.FrameC.DialogD.Panel5-3 下列关于实现图形用户界面的描述中,错误的是DA.放在容器中的组件首先要定义,接着要初始化B.放在容器中的多个组件是要进行布局的,默认的布局策略是FlowLayoutC.容器中所有组件都是事件组件,都可以产生事件对象D.事件处理是忧监听者定义的方法来实现的5-4 下列关于组件类的描述中,错误的是AA.组件类中包含了文本组件类(TextComponent)和菜单组件类(MenuComponent)B.标签(Label)和按钮(Button)是组件类(Component)的子类C.面板(Panel)和窗口(Window)是容器类(Container)的子类D.文本框(TextField)和文本区(TextArea)是文本组件类(TextComponent)的子类5-5 在对下列语句的解释中,错误的是Cbut.addActionListener(this);A.but是某种事件对象,如按钮事件对象B.t his表示当前容器C.A ctionListener是动作事件的监听者D.该语句的功能是将but对象注册为this对象的监听者5-6 所有事件类的父类是CA.ActionEvent B.AwtEvent C.KeyEvent D.MouseEvent5-7 所有GUI标准组件类的父类是CA.Buttom B.List C.Component D.Container5-8 下列各种布局管理器中Window类、Dialog类和Frame类的默认布局是CA.FlowLayout B.CardLayout C.BorderLayout D.GridLayout5-9 在下列各种容器中,最简单的无边框的又不能移动和缩放的只能包含在另一种容器中的容器是D A.Window B.Dialog C.Frame D.Panel5-10 下列关于菜单和对话框的描述中,错误的是CA.Frame容器是可以容纳菜单组件的容器B.菜单条中可包含若干个菜单,菜单中又可包含若干菜单项,菜单项中还可包含菜单子项C.对话框与Frame一样都可作为程序的最外层容器D.对话框内不含有菜单条,它由Frame弹出5-1 AWT是抽象窗口工具包的英文缩写。
(对)5-2 容器中只能包含有组件,而不能再含有容器。
(错)5-3 容器分可以独立的窗口和不可以独立的窗口两种。
(对)5-4 单选按钮提供“多选一”的输入选择,下拉列表提供“多选多”的输入选择。
(错)5-5 所有容器的默认布局都是FlowLayout。
(错)5-6 所有的组件都是事件源。
(错)5-7 Java 2 的事件处理方法是采用委托事件处理模型。
(对)5-8 事件组件都应注册一个事件监听者。
(对)5-9 事件监听者除了得知事件的发生外,还应调用相应方法处理事件。
(对)5-10 所有事件的父类是EventObject类。
(对)5-11 图形用户界面是由用户自定义成分、控制组件和容器组成的。
(对)5-12 所有GUI标准组件类的父类是Component类。
(对)5-13 所有容器类的父类是Frame类。
(错)5-14 标准和按钮都是事件源。
(对)5-15 文本去和文本框都可以引发两种事件:文本改变事件和动作事件。
(错)5-16 每个复选框有两种状态:“打开”和“关闭”状态。
(对)5-17 复选框组(CheckboxGroup)是由若干个按钮组成的。
在一组按钮中可选多个。
(错)5-18 列表(List)是由多个选项组成的,只可在列表框的若干个选项选取一个。
(错)5-19 下拉列表(Choice)是一种“多选多”的输入界面。
(错)5-20 滚动条有两类:水平滚动条和垂直滚动条。
(对)5-21 画布(Canvas)是一种可容纳多个组件的容器。
(错)5-22 所有容器都采用顺序布局(FlowLayout)作为默认布局管理器。
(错)5-23 边界布局(BorderLayout)将容器分为东、西、南、北共4个区域。
(错)5-24 卡片布局(CardLayout)可使容器容纳多个组件,在同一时刻只显示若干个组件中的一个。
(对)5-25 容器可容纳组件和容器,同一个容器中的组件可被同时显示或者同时隐藏。
(对)5-26 所有容器都是有边框的。
(错)5-27 Panel容器是可以嵌套使用的。
(对)5-28 Applet实际是一种特殊的Panel容器。
Java Applet程序只负责它拥有的Applet容器内的无边框区域。
(对)5-29窗口(Window)容器是一种独立窗口,但它不能作为程序的最外层容器。
(对)5-30 Frame容器是有边框的容器,它也是一种独立窗口,只能作为最外层容器。
(对)5-31 Frame容器可以容纳菜单组件,它实现了MenuContainer接口。
(对)5-32 MenuComponent类是菜单组件的父类。
(对)5-33 菜单条(MunuBar)、菜单(Munu)、菜单项(MunuItem)是3中不同的菜单组件。
(错)5-34 对话框(Dialog)不是一种独立使用的容器。
(错)5-35 文件对话框()是对话框(Dialog)的子类,它是一种打开文件和保留文件的对话框窗口。
(对)分析程序输出结果5-1 Exer5_1.javaimport java.applet.*;import java.awt.*;public class Exer5_1 extends Applet{private Label lab1,lab2;public void init(){lab1=new Label();lab1.setText("标签文本左对齐");lab1.setAlignment(Label.LEFT);lab2=new Label("标签文本右对齐",Label.RIGHT);setLayout(new GridLayout(3,3));add(lab1);add(lab2);}}运行改程序后,输出结果如图5-5所示。
图5-5 分析题5-1输出结果5-2 Exer5_2.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;public class Exer5_2 extends Applet implements ActionListener,ItemListener{List colList;String colName[]={"黑色","蓝色","浅蓝色","绿色","红色","黄色"};Color cols[]={Color.black,Color.blue,Color.cyan,Color.green,Color.red,Color.yellow};int t;public void init(){colList=new List(4,false);colList.addActionListener(this);colList.addItemListener(this);for(int i=0;i<colName.length;i++)colList.add(colName[i]);add(colList);}public void actionPerformed(ActionEvent e){}public void itemStateChanged(ItemEvent e){showStatus(colList.getSelectedItem()+";index"+colList.getSelectedIndex());t=colList.getSelectedIndex();repaint();}public void paint(Graphics g){g.setColor(cols[t]);g.fillRect(15,30,20,20);}}运行改程序后,输出结果如图5-6所示。
5-3 Exer5_3.javaimport java.awt.*;import java.awt.event.*;public class Exer5_3 extends Frame implements ActionListener{Frame fr;Panel deck;CardLayout c1;Button but[];String name[]={"第一张","下一张","前一张","最末张"};public Exer5_3(){fr=new Frame("卡片窗口");deck=new Panel();c1=new CardLayout();deck.setLayout(c1);Panel c1=new Panel();Label lab1=new Label("卡片1");c1.add(lab1);deck.add(c1,lab1.getText());Panel c2=new Panel();Label lab2=new Label("卡片2");c2.add(lab2);deck.add(c2,lab2.getText());Panel c3=new Panel();Label lab3=new Label("卡片3");c3.add(lab3);deck.add(c3,lab3.getText());Panel c4=new Panel();Label lab4=new Label("卡片4");c4.add(lab4);deck.add(c4,lab4.getText());Panel contr=new Panel();contr.setLayout(new GridLayout(2,2));but=new Button[name.length];for(int i=0;i<name.length;i++){but[i]=new Button(name[i]);but[i].addActionListener(this);contr.add(but[i]);}fr.add(contr,BorderLayout.WEST);fr.add(deck,BorderLayout.EAST);fr.setSize(300,150);fr.show();}public void actionPerformed(ActionEvent e) {if(e.getSource()==but[0])c1.first(deck);if(e.getSource()==but[1])c1.next(deck);if(e.getSource()==but[2])c1.previous(deck);if(e.getSource()==but[3])st(deck);}public static void main(String args[]){Exer5_3 m1=new Exer5_3();}}运行该程序后,输出结果如图5-7所示。