发布时间 : 星期三 文章Java2实用教程(第三版)课后答案 - 耿祥义主编更新完毕开始阅读65b0f7637e21af45b207a806
}
public class Test {
public static void main(String args[]) {
B b=new B();
System.out.println(\我调用方法f输出英文字母表:\b.f();
System.out.println(\我调用方法g输出希腊字母表:\b.g(); } }
17.编写一个异常类MyException,再编写一个类Student,该类有一个产生异常的方法public void speak(int m) throws MyException,要求参数m的值大于1000时,方法抛出一个MyException对象。最后编写主类,在主类的main方法中用Student创建一个对象,让该对象调用speak方法。 答: class MyException extends Exception {
String str1;
MyException(int m) {
str1=m+\出现错误 可能造成的原因是取值大于1000\}
public void showStr1() {
System.out.println(str1); } }
class Student {
public void speak(int m) throws MyException {
if(m>1000) {
MyException exception=new MyException(m); throw exception; } else
System.out.println(m); } }
public class Test {
13
public static void main(String agrs[]) {
int m;
Student stu1=new Student(); m=987; try {
stu1.speak(m); m=1234;
stu1.speak(m); }
catch(MyException e) {
e.showStr1(); } } }
18.编写一个类,该类有一个方法public int f(int a,int b),该方法返回a和b的最大公约数。然后再编写一个该类的子类,要求子类重写方法f,而且重写的方法将返回a和b的最小公倍数。要求在重写的方法的方法体中首先调用被隐藏的方法返回a和b的最大公约数m,然后将乘积(a*b)/m返回。要求在应用程序的主类中分别使用父类和子类创建对象,并分别调用方法f计算两个正整数的最大公约数和最小公倍数。 答: class A {
public int f(int a,int b) {
if(a
int temp=0; temp=a; a=b; b=temp; }
int r=a%b; while(r!=0) { a=b; b=r; r=a%b; }
return b; } }
14
class B extends A {
public int f(int a,int b) {
int m;
m=super.f(a,b); return (a*b)/m; } }
public class Test {
public static void main(String args[]) {
A a=new A();
System.out.println(\和102的最大公约数是:\B b=new B();
System.out.println(\和102的最小公倍数是:\} }
第5章 字符串
1. 使用String类的public String toUpperCase()方法可以将一个字符串中的小写字母变成大写字母,使用public String toLowerCase()方法可以将一个字符串中的大写字母变成小写字母。编写一个程序,使用这两个方法实现大小写的转换。
答: class Test {
public static void main(String args[]) {
String str=\
System.out.println(\要转换的字符串是:\String s=str.toUpperCase();
System.out.println(\转换成大写字符串是:\s=str.toLowerCase();
System.out.println(\转换成小写字符串是:\} }
2. 使用String类的public String concat(String str)方法可以把调用该方法的字符串与参数指定的字符串连接,把str指定的串连接到当前串的尾部获得一个新的串。编写一个程序通过连接两个串得到一个新串,并输出这个新串。 答: class Test {
public static void main(String args[])
15
{
String str1=\String str2=\
String s=str1.concat(str2);
System.out.println(\将字符串\与字符串\连接后得到的新字符串是:\
System.out.println(s); } }
3. String类的public char charAt(int index)方法可以得到当前字符串index位置上的一个字符。说出下列程序的输出结果。 public class E3 {
public static void main(String args[]) {
String s=\中国科学技术大学\
char a=s.charAt(2),b=s.charAt(6); System.out.print(a); System.out.println(b); } }
答: 科大
4. 使用java.util包中的Arrays类的静态方法public static void sort(double a[])可以把参数a指定的double型数组按升序排序,使用java.util包中的
Arrays类的静态方法public static void sort(double a[],int start,int end)可以把参数a指定的double型数组中从位置start到end-1位置的数按升序排序。写出下列程序的输出结果。 import java.util.*; public class E4 {
public static void main(String args[]) {
int a[]={23,67,89,90,-987};
double b[]={12.89,90.87,34,678.987,-98.78,0.89}; Arrays.sort(a);
Arrays.sort(b,1,4); for(int i=0;i<=4;i++) {
System.out.print(a[i]+\}