解析JAVA程序设计方案第五章课后答案
- 格式:docx
- 大小:12.62 KB
- 文档页数:7
第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。
习题一、选择题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初始值,再为该类定义加、减、乘、除等公有方法,分别对两个成员变量执行加减乘除的运算。
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章 Java语言面与向对象的程序设计1. Java语言有哪些主要特点?答:〔要点〕:1.简单易学2.面向对象3.平台无关性4.安全稳定5.支持多线程6.很好地支持网络编程7.Java丰富的类库使得Java可以广泛地应用2.简述面向过程问题求解和面向对象问题求解的异同。
试列举出面向对象和面向过程的编程语言各两种。
答:面向过程问题求解,以具体的解题过程为研究和实现的主体,其思维特点更接近于电脑;面向对象的问题求解,则是以“对象”为主体,“对象”是现实世界的实体或概念在电脑逻辑中的抽象表示,更接近于人的思维特点。
面向过程的编程语言:C,Pascal,Foratn。
面向对象的编程语言:C++,Java,C#。
3.简述对象、类和实体及它们之间的相互关系。
尝试从日常接触到的人或物中抽象出对象的概念。
答:面向对象技术中的对象就是现实世界中某个具体的物理实体在电脑逻辑中的映射和表达。
类是同种对象的集合与抽象。
类是一种抽象的数据类型,它是所有具有一定共性的对象的抽象,而属于类的某一个对象则被称为是类的一个实例,是类的一次实例化的结果。
如果类是抽象的概念,如“电视机”,那么对象就是某一个具体的电视机,如“我家那台电视机”。
4.对象有哪些属性?什么是状态?什么是行为?二者之间有何关系?设有对象“学生”,试为这个对象设计状态与行为。
答:对象都具有状态和行为。
对象的状态又称为对象的静态属性,主要指对象内部所包含的各种信息,也就是变量。
每个对象个体都具有自己专有的内部变量,这些变量的值标明了对象所处的状态。
行为又称为对象的操作,它主要表述对象的动态属性,操作的作用是设置或改变对象的状态。
学生的状态:、性别、年龄、所在学校、所在系别、通讯地址、号码、入学成绩等;学生的行为:自我介绍、入学注册、选课、参加比赛等。
5.对象间有哪三种关系?对象“班级”与对象“学生”是什么关系?对象“学生”与对象“大学生”是什么关系?答:对象间可能存在的关系有三种:包含、继承和关联。
《Java程序设计》课后习题参考答案Java程序设计课后习题参考答案1. 介绍在 Java 程序设计课程中,课后习题是帮助学生巩固知识、加深理解和提高编程能力的重要环节。
本文将为大家提供《Java程序设计》课后习题的参考答案,以帮助学生更好地学习和掌握 Java 编程。
2. 基本概念Java 程序设计课后习题涵盖了从基础到高级的各种知识点,包括但不限于变量、数据类型、条件语句、循环语句、数组、类、对象、继承、多态等内容。
通过解答这些习题,学生可以加深对这些概念的理解,并且通过实际操作来巩固他们的编程能力。
3. 习题解答策略当解答课后习题时,以下几个策略可以帮助你更好地理解和解决问题:3.1 仔细阅读题目要求。
确保自己充分理解题目所要求的功能和目标。
3.2 分析问题。
在着手解答问题之前,先理清思路,分析问题的要点和关键部分。
3.3 设计算法。
根据问题的要求,设计一个合适的算法来解决问题。
3.4 编写代码。
用 Java 编程语言将你设计的算法转化为代码实现。
3.5 测试和调试。
对编写的代码进行测试和调试,确保程序能够正常运行,并且得到正确的结果。
4. 习题参考答案示例下面我们将列举几个常见的习题参考答案示例,以帮助大家更好地理解和学习 Java 程序设计:4.1 变量与数据类型:习题要求定义一个整型变量并赋值为10,然后输出该变量的值。
```public class VariableExample {public static void main(String[] args) {int num = 10;System.out.println("变量的值为:" + num);}}```4.2 条件语句:习题要求判断一个数是否是偶数,如果是,则输出“偶数”,否则输出“奇数”。
```public class EvenOddExample {public static void main(String[] args) {int num = 5;if (num % 2 == 0) {System.out.println("偶数");} else {System.out.println("奇数");}}}```4.3 循环语句:习题要求输出1到10之间的所有偶数。
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;。
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) + ")");}}。
第五章编程题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) 将字符串中每个单词的第一个字母变成大写,输出到控制台。
1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protecte及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。
第5章习题解答1.流的主要特征有哪些,用流来实现JAVA中的输入输出有什么优点?答:一是单向性,即数据只能从数据源流向数据宿:二是顺序性,先从数据源流出的数据一左比后流出的数据先到达数据宿:三是数据流必须而且只能和一个数据源与一个数据宿相连。
优点是体现了面向对象程序设计的概念,通过流可以把对不同类型的输入/输出设备的操作统一为用流来实现。
2.对字廿流和字符流进行读写操作的一般步骤是什么?答:声明流对象,创建流对象,通过流对象进行读(写)操作,关闭流对象。
3.有哪些常用的字节流和字符流,他们的主要区别是什么?答:InputStream/OutputStrem:普通字iT 流,所有字I'J流的基类。
FilelnputStream/ FileOutputStream :用于从文件中读写数据。
BufferedlnputStream/ BufferedOutputStream:用于从缓冲区输入流中读写数据。
采用缓冲区流可减少实际上从外部输入设备上读写数据的次数,从而提高效率。
DatalnputStream/ DataOutputStream:按读写数据对象的大小从字节流中读写数据,而不是象其它字节流那样以字节为基本单位。
PipedlnputStream/ PipedOutputStream:管道输流用于从另一个线程中读写数据。
4.么是异常?说明Java中的异常处理机制?试述JAVA中异常的抛出和传递过程?答:异常是程序设计语言提供的一种机制,它用于在程序运行中的非常规情况下,控制程序对非常规情况进合理的处理。
Java提供了try-catch-finally语句来对异常进行处理。
先按照正常顺序执行try子句中的语句,若在执行过程中出现异常,则try子句中还未被执行的语句将再也不会被执行。
而程序控制立即转移到catch子句,将发生的异常与catch子句中的异常进行匹配,若找到一个匹配,就执行该catch子句中的语句。
处理完异常后,还要执行finally子句中的语句。
若没有一个catch子句中的异常与发生的异常匹配,则catch 子句就不会被执行,但还是要执行finally子句中的语句。
若在执行try子句中的语句时没有发生异常,则catch子句不被执行,但finally子句中的语句还是会被执行。
当一个方法中没有对所发生的异常进行处理,则该异常将被抛出,由调用该方法的方法来处理,这样可以一直往上抛,直至由系统来处理。
5.如何改进下而的程序以提髙其执行性能?对你的改进作岀解释,并写出新的程序。
int i0URL url 二new URL ("http://java. sun. com/'")。
URLConnection javaSite = url. openConnection0 oInputStream input 二javaSite. getInputStream0 oInputStreamReader reader = new InputStreamReader(input)o while ((i = reader.readO) != -1) {System・ out・ print(i)。
}答:使用缓冲流!在这里,可以增加两个缓冲流:在InputStream上增加一个BufferedlnputStream ,在InputStreamReader 上增加一个BufferedReadero 改变后的程序如V:int i oURL url = new URL C'http: / / java .sun .com/")。
URLConnection javaSite = url. openConnection0 oInputStream input = javaSite・getInputStream() «>BufferedlnputStream in = new BufferedlnputStream(input)oBufferedReader reader = new BufferedReader(new InputStreamReader(in))0while ((i = reader・read()) != T) {System・ out・ print(i)。
6.査阅API文档中有关DatalnputStream和DataOutputStream的内容。
并编写一个程序使用readlnt 0方法从输入文件中读入学生成绩,求岀学生的总成绩和平均成绩输岀到另一个文件中。
假设输入文件中的内容格式如下:姓名语文数学外语张三89 92 95李四77 81 74干石87 80 757.左义一个学生类,它包含如下信息:学生姓名,性别,年龄,成绩。
试编写一有如下功能的程序。
若命令行带参数C,用户通过键盘输入学生信息并保存到一文件中;若命令行带参数E,用户可对某一学生的成绩修改;若命令行带参数D,用户可删除某一学生的信息;若命令行带参数A,用户可向文件中加入更多学生的信息。
8.设计一个程序读入一个文本文件,对英中岀现的字符数进行统计,最后输岀每个字符在文件中出现的次数。
9.设计一文件过滤程序,读入一个文件的内容。
将文件中所有包含“我不喜欢Java”的字样过滤掉,将过滤后的内容存入另一文件中。
10.下面的程序合法吗?try {} finally {}答:合法。
11.下面的程序片断能捕获什么异常?catch (Exception e) {}这样的异常处理有什么不好吗?答:该程序片段将捕获Exception类异常,由于所有异常都是Exception类的子类,因此,实际上该程序片段将对所有异常都进行同样地处理。
而不能根拯具体的异常作出不同的处理方式。
12.下面的程序片断有什么错误吗?它能否通过编译?try {} catch (Exception e) {} catch (ArithmeticException a) {}答:由于第一个catch子句将捕获所有异常,因此,第二个catch子句永远不会被执行。
不能通过编译。
13阅读程序,写岀程序的运行结果。
class first_exception{public static void main(String args[]) { char Coint a,b=0oint [] arra3r=new int [7] GString s二"Hello"。
try{a二1/b。
}catch(ArithmeticException ae){System・ out・ printin("Catch "+ae)。
array[8]=0o}catch(ArraylndexOutOfBoundsException ai) { System・ out・ printin("Catch "+ai)。
}try{c=s・ charAt(8)。
}catch(StringlndexOutOfBoundsException se){ System・ out・ printin("Catch "+se)。
}}}14.“强制异常就是指系统左义的异常,非强制异常就是指用户定义的异常”,这样的叙述正确吗?为什么?答:不正确,系统泄义的异常中也有非强制异常。
15.在例5-12中,如何改进程序以阻止异常从method方法传递到main方法?你认为在什么情况下不对异常进行处理,而使用异常传递由上一层类来处理比较合适?16.“关键字throw用于抛出单个异常,关键字throws用于抛岀多个异常”这一说法正确吗?为什么?答:不正确,throws用于在方法首部中声明该方法要抛岀的异常。
17.改正下而的程序使其能通过编译。
public class cat {void test (File named) {BufferedReader input = null。
String line = nullotry{input = new BufferedReader(new FileReader(named))owhile ((line = input.readLineO) != null) {System・ out・ println(line)。
returrio} finally {if (input != null) { input・closeO °}}}}答:public static void cat (File named) {RandomAccessFile input = null。
String line = null®input = new RandomAccessFile(named, r")。
while ((line = input・:r"dLine()) != null) {System・ out・ printin (line)。
returnc} catch(FileNotFoundException fnf) {System. err・println("File: " + named + " not found・")。
} catch(Exception e) {System・ err・ printin(e・ toString ())。
} finally {if (input != null) {try {input・closeO ◎} catch(IOException io) {}}}}18•阅读API文档中有关F订e类的描述,并编写一个程序在屏幕上输出一个给泄文件的有关信息。
19.试编写一个程序读入英文的Zero到Nine,输出貝对应的阿拉伯数字,要求能对错误的输入按异常情况进行处理。
20.设计一个文件分割程序和文件合并程序,文件分割程序能将一个文件分割为指泄大小的多个文件。
文件合并程序能将多个文件合并为一个文件(要求能对文件操作中的异常情况进行合理的处理)O。