JAVA语言程序设计基础篇原书第八版上机编程题 下载本文

High Level Programming Language Java Assignments and Programming Exercises

高级语言程序设计Java

作业和上机练习题 原书第八版

Chapter 1 Introduction to Computers, Programs, and Java

Programming Exercise: 1.1

1.1 为程序清单1-1创建名为Welcome.java的文件,可以使用任何编辑器,将该文件保存为文本格式。

public class Exercise01_01 {

public static void main(String[] args) { System.out.println(\

System.out.println(\ System.out.println(\ } }

Chapter 2 Elementary Programming 第二章 基本程序设计Programming Exercises: 2.3, 2.7

2.3

import java.util.Scanner;

public class Exercise02_03 {

public static void main(String[] args) { // TODO Auto-generated method stub Scanner input =new Scanner(System.in); System.out.println(\ int feet = input.nextInt();

double meters = feet * 0.305;

System.out.println(feet +\ } } 2.7

import java.util.Scanner;

public class Exercise02_07 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println(\ int minutes = input.nextInt();

int hours = minutes / 60 ;

2

int days = hours / 24 ;

int years = days / 365 ;

int remainingdays = days % 365 ;

System.out.print(minutes + \is approximately\+ years + \+ remainingdays + \ } }

Chapter 3 Selections 第三章 选择

Programming Exercises: 3.6, 3.7, and 3.19 3.6

import java.util.Scanner; public class Exercise03_06 {

public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.print(\ double weight = input.nextDouble();

System.out.print(\ double feet = input.nextDouble(); double inches = input.nextDouble();

final double KILOGRAM_PER_POUND = 0.45359237; final double METER_PER_INCH = 0.0254; final double METER_PER_FEET = 0.3048;

double weightInKilograms = weight * KILOGRAM_PER_POUND;

double heightInMeters = feet * METER_PER_FEET + *METER_PER_INCH;

double bmi = weightInKilograms / (heightInMeters*heightInMeters);

System.out.println(\ if (bmi < 16)

System.out.println(\ else if (bmi < 18)

System.out.println(\

inches 3

else if (bmi < 24)

System.out.println(\ else if (bmi <29)

System.out.println(\ else if (bmi <35)

System.out.println(\ else

System.out.println(\ } } 3.7

import java.util.Scanner; public class Exercise03_07 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print(\ double amount = input.nextDouble();

int remainingAmount = (int)(amount*100);

int numbersOfOneDollars = remainingAmount /100; remainingAmount = remainingAmount 0;

int numbersOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount %;

int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount ;

int numberOfNickels = remainingAmount /5; remainingAmount = remainingAmount %5;

int numberOfPennies = remainingAmount;

String output = \

numbersOfOneDollars + ((numbersOfOneDollars>1)?\ numbersOfQuarters + ((numbersOfQuarters>1)?\ numberOfDimes + ((numberOfDimes>1)?\ numberOfNickels + ((numberOfNickels>1)?\ numberOfPennies + ((numberOfPennies>1)?\

4

System.out.println( output ); } }

3-19 Write a program that reads three edges for a triangle and determines whether the input is valid. The input is valid if the sum of any two edges is greater than the third edge. For example, if your input for the three edges is 1, 2, and 1, the output should be: Can edges 1,2, and 1 form a triangle? False

3.19 (三角形有效性验证)编写程序,读入三角形的三条边并确定输入是否有效。如果任意两条边的和大于第三条边则输入有效。例如,如果输入的三条边是1,2,1,输出应该是: Can edges 1, 2, and 1 from a triangle? false

如果输入的三条边是2,2,1,输出应该是: Can edges 2, 2 and 1 from a triangle? True import java.util.Scanner; public class Exercise03_19 {

public static void main(String args[]) {

Scanner input = new Scanner(System.in); System.out.println(\ double sideA = input.nextDouble(); double sideB = input.nextDouble(); double sideC = input.nextDouble();

boolean triangle =

(sideA + sideB > sideC && sideA + sideC > sideB && sideB + sideC > sideA);

System.out.println(\edges\+ sideA +\+ \+ sideC + \a triangle ?\triangle);

if(triangle == true)

{double perimeter = sideA+sideB+sideC;

System.out.print(\ } else {

System.out.println(\ } } }

5

Chapter 4 Loops 第四章 循环

Programming Exercises: 4.3, 4.17, and 4.19 (5.3, 5.17, and 5.19 in the 10th LiveLab )

4.3

public class Exercise05_03 {

public static void main(String[] args) {

System.out.println(\ pounds\ int i =1;

double j= 2.2; while (i<200){ System.out.println(i+\ \ i++; j=i*2.2; } } } 4.17

import java.util.Scanner; public class Exercise05_17 { public static void main(String[] args) { // TODO Auto-generated method stub

System.out.print(\ Scanner input = new Scanner(System.in); int lines = input.nextInt();

for (int row = 1;row<=lines;row++){ for(int space=1;space<= lines - row;space++ ) System.out.print(\ for(int m = row; m>=1;m--) System.out.print(m); for(int n =2;n<=row;n++) System.out.print(n);

System.out.println(); } } }

6

4.19

public class Exercise05_19 {

public static void main(String[] args){

for (int row = 1;row<=8;row++){ for(int space=1;space<= 8 - row;space++ ) System.out.print(\ \ for(int m =1; m<=row;m++) System.out.print((int)Math.pow(2,m-1)+\ for(int n =row;n>=2;n--) System.out.print((int)Math.pow(2,n-2)+\

System.out.println(); } } }

7

Chapter 5 Methods 第五章 方法

Programming Exercises: 5.5, 5.9, and 5.19 (6.5, 6.9, and 6.19 in the 10th LivLab)

5.5 (Sorting three numbers) Write the following method to display three numbers in increasing order. Use the following method header: public static void sort(double d1, double d2, double d3)

2 (对三个数排序)编写以下方法,按升序显示三个数。

public static void sort(double num1, double num2, double num3) import java.util.Scanner; public class Exercise06_05 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.println(\ double i = input.nextDouble(); double y = input.nextDouble(); double z = input.nextDouble(); displaySortedNumbers(i,y,z); }

public static void displaySortedNumbers(double num1,double num2,double num3){ if(num1>=num2&&num2>=num3) System.out.println(num3+\ if(num3>=num1&&num1>=num2) System.out.println(num2+\ if(num1>=num3&&num3>=num2) System.out.println(num2+\ if(num3>=num2&&num2>=num1) System.out.println(num1+\ if(num2>=num3&&num3>=num1) System.out.println(num1+\ if(num2>=num1&&num1>=num3) System.out.println(num3+\

8

} }

5.9

public class Exercise06_09 {

public static void main(String[] args) {

System.out.print(\ Meters Meters Feet\ System.out.println(); double chujiao = 1.0; double chumi = 20.0; for(int i = 1;i<=10;i++){

double jiemi = footToMeter(chujiao); double jiejiao = meterToFoot(chumi);

System.out.println(chujiao+\ \\

chujiao++;

chumi = chumi+5.0; } }

public static double footToMeter(double foot){ double meter = foot*0.305; return meter; }

public static double meterToFoot(double meter){ double foot = meter/0.305; return foot; } } 5.19

import java.util.Scanner; /** Design: ... */

/** Coding: Please indent and format your code properly */ /** Copy and paste your code to replace the template below */ /** Note that your class must be named Exercise06_19 */

public class Exercise06_19 {

public static void main(String[] args){

System.out.println(\ Scanner input = new Scanner(System.in);

\ \9

double num1= input.nextDouble(); double num2= input.nextDouble(); double num3= input.nextDouble();

System.out.print(\ if(isValid(num1,num2,num3)){

System.out.print(\ } else{

System.out.print(\ } }

public static boolean isValid(double num1,double num2,double num3){ if(num1+num2>num3&num2+num3>num1&num1+num3>num2){ return true;} else {

return false; } }

public static double area(double num1,double num2,double num3){ double s=(num1+num2+num3)/2;

double area = Math.sqrt(s*(s-num1)*(s-num2)*(s-num3)); return area; } }

Chapter 6 Single-Dimensional Arrays 第六章 一维数组

Programming Exercises: 6.1, 6.3, and 6.11 (7.1, 7.3, and 7.11 in the 10th LivLab)6.1

import java.util.Scanner; public class Exercise07_01 { public static void main(String[] args) { // TODO Auto-generated method stub

System.out.println(\ Scanner input = new Scanner(System.in); int number = input.nextInt(); int best = 0;

int[] grades = new int[number];

System.out.println(\ for(int i =0;i

10

if(grades[i]>best) best = grades[i]; }

for(int i = 0;i=best - 10) System.out.println(\ else if (grades[i]>=best - 20) System.out.println(\ else if (grades[i]>= best - 30) System.out.println(\ else if (grades[i]>= best - 40) System.out.println(\ else System.out.println(\ } } }

6.3 Write a program that reads ten numbers and displays distinct numbers (i.e., if a numbers appears multiple times, it is displayed only once). Hint: read a number and store it to an array if it is new. If the number is already in the array, discard it. After the input, the array contains the distinct numbers.

6.3 (输出不同的数)编写一个程序,读入10个数并且显示其中相互不同的数(即一个数多次出现,仅显示一次)。提示:读入一个数,如果它是一个新数,则把它存储在数组中;如果数组中已有该数,则把它丢弃。输入结束后,数组中的数都是不同的数。 import java.util.Scanner; public class Exercise07_03 {

public static void main(String[] args) { // TODO Auto-generated method stub int[] count = new int[100];

System.out.println(\ Scanner input = new Scanner(System.in); int integer = input .nextInt(); while(integer != 0){ count[integer-1]++; integer = input.nextInt(); }

for (int i = 0; i < 100; i++) { if (count[i] > 0) System.out.println((i+1) + \

11

+ ((count[i] == 1) ? \ } } } 6.11

import java.util.Scanner; public class Exercise07_11 {

public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print(\ int numberOfNum = 10; int mean = 0; int deviation =0;

double[] numbers = new double[numberOfNum]; for(int i = 0; i

System.out.print(\

System.out.print(\ }

public static double mean(double[] numbers){ double sum = 0;

for(int i = 0; i

double mean = sum/10.0; return mean; }

public static double deviation(double[] numbers){ double sum = 0;

for(int i = 0; i

double mean = sum/10.0;

double x = 0;

for(int i = 0; i

double deviation = Math.sqrt(x/9);

12

return deviation; } }

Chapter 8 Objects and Classes 第八章 对象和类

Programming Exercises: 8.1, 8.7, 8.9, and 8.11 (9.1, 9.7, 9.9, and 9.11 in the 10th LivLab)

8.1 The Rectangle class

Design a class named Rectangle to represent a rectangle. The class contains:

? Two double data fields named width and height with default values to 1.0 to

denote the width and the height of the rectangle. ? A string data field named color that specifies the color of a rectangle. The

default value is white. ? A no-arg constructor that creates a default rectangle. ? A constructor that creates a rectangle with the specified width and height. ? The accessor and mutator methods for all three data fields ? A method named getArea() that returns the area of this rectangle. ? A method named getPerimetet() that returns the perimeter of this

rectangle. ? A method named toString() that returns a string to descript the rectangle. The formula to compute the area of a rectangle: width*height . The toString() method is implemented as follows:

Return “Rectangle: width= ” + width + “ height = ”+ height;

Write a test program that creates two Rectangle object. Assign width 5 and height 15 to the first object and width 4.3 and height 40.5 to the second object. Assign color yellow to both Rectangle objects .Displays the properties of both objects and find their areas and perimeters.

1 (矩形类Rectangle)编写名为Rectangle的类表示矩形,这个类包括:

? 两个double类型的数据域width和height表示矩形的宽和高,它们的默认值都为1; ? String类型的数据域color表示矩形的颜色,进一步假设所有矩形的颜色都是相同的,

默认颜色为白色;

? 无参构造方法创建默认矩形;

? 一个构造方法创建指定width和height的矩形; ? 所有三个数据域的访问器方法和修改器方法; ? getArea()方法返回该矩形的面积; ? getPerimeter()方法返回它的周长;

画出该类的UML图并实现它。编写一个测试程序,创建两个Rectangle对象,设置第一个对象的宽为4,高为40,第二个对象的宽为3.5,高为35.9,所有Rectangle对象的颜色为红色。显示两个对象的属性并求它们的面积和周长。

13

public class Exercise09_01 {

public static void main(String[] args) {

Rectangle myRectangle = new Rectangle(4, 40);

System.out.println(\ myRectangle.width + \ myRectangle.height + \ myRectangle.getArea());

System.out.println(\ myRectangle.getPerimeter());

Rectangle yourRectangle = new Rectangle(3.5, 35.9);

System.out.println(\ yourRectangle.width + \ yourRectangle.height + \ yourRectangle.getArea());

System.out.println(\ yourRectangle.getPerimeter()); } }

class Rectangle { double width; double height; Rectangle(){ width = 1.0; height = 1.0; } Rectangle(double newWidth , double newHeight){ width = newWidth; height = newHeight; }

double getArea(){ return width*height; }

double getPerimeter(){ return (width+height)*2.0; } } ` 8.7

(The Account class) Design a class nanmed Account that contains:

14

? A private int data field named id for the account (default 0).

? A private double data field named balance for the account (default 0).

? A private double data field named annualInterestRate that stores the current int

erest rate (default 0). Assume all accounts have the same interest rate.

? A private Date data field named datecreated that stores the date when the accou

nt was created

? A no-arg constructor that creates a default account.

? A constructor that creates an account with the specified id and initial balance. ? The accessor and mutator methods for id, balance, and annualInterestRate, ? The accessor method for datecreated.

? A method named getmonthlylnterestRateo that returns the monthly interest rate ? A method named withdraw that withdraws a specified amount from the account ? A method named deposit that deposits a specifred amount to the account.

Draw the UML diagram for the class. Implement the class. Write a test program that creates an Account object with an account ID of 1122, a balance of $20,000 and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the monthly interest, and the date when this account was created.

8.7 (账户类Account)设计一个名为Account的类模拟账户,它包括: ? int型数据域id表示账号(默认值为0);

? double型数据域balance表示账户余额(默认值为0);

? double型数据域annualInterestRate存储当前年利率(默认值为0); ? Date型数据域dateCreated存储账户的开户日期; ? 无参构造方法创建一个默认的账户;

? id,balance和annualInterestRate的访问器和修改器; ? dateCreated的访问器;

? getMonthlyInterestRate()方法返回月利率; ? withdraw方法从账户提取特定数额的款; ? deposit方法向账户存特定数额的款;

画出该类的UML图并实现它。编写一个测试程序,创建一个账号为1122、余额为20000、年利率为4.5%的Account对象。使用withDraw方法提款2500美元,使用deposit方法存款3000美元,并打印余额和月利率,以及该账户的开户日期。

import java.util.Date;

public class Exercise09_07 {

public static void main(String[] args) { Account account = new Account(1122, 20000); Account.setAnnualInterestRate(4.5); account.withdraw(2500); account.deposit(3000); System.out.println(\ System.out.println(\ account.getMonthlyInterest()); System.out.println(\

15

account.getDateCreated()); } }

class Account { // Implement it private int id; private double balance; private static double annualInterestRate; private Date dateCreated;

Account(){ id = 0; balance = 0; annualInterestRate = 0; dateCreated = new Date(); }

Account(int newId,double newBalance){ id = newId; balance = newBalance; dateCreated = new Date(); }

public int gerId(){ return id; }

public double getBalance(){ return balance; }

public double getAnnualInterestRate(){ return annualInterestRate; }

public void setId(int newId){ id = newId; }

public void setBalance(double newBalance){ balance = newBalance; }

public static void setAnnualInterestRate(double newAnnualInterestRate){ annualInterestRate = newAnnualInterestRate; }

public Date getDateCreated(){ return dateCreated; }

16

public void withdraw(double tiqu){ balance -= tiqu; }

public void deposit(double cunjin){ balance += cunjin; }

public double getMonthlyInterest(){ return balance*annualInterestRate/12; } } 8.9

public class Exercise09_09 {

public static void main(String[] args) { // TODO Auto-generated method stub RegularPolygon polygon1 = new RegularPolygon(); RegularPolygon polygon2 = new RegularPolygon(6, 4); RegularPolygon polygon3 = new RegularPolygon(10, 4, 5.6, 7.8); System.out.println(\ polygon1.getPerimeter()); System.out.println(\ System.out.println(\ polygon2.getPerimeter()); System.out.println(\ System.out.println(\ polygon3.getPerimeter()); System.out.println(\ } }

class RegularPolygon { // Implement it //?? private int n = 3; //?? private double side = 1; //??x?? private double x = 0; //??y?? private double y = 0; RegularPolygon(){

17

} RegularPolygon(int n1 , double side1){ n = n1; side = side1; } RegularPolygon(int n2 , double side2, double x2, double y2){ n = n2; side = side2; x= x2; y = y2; }

public int getN(){ return n; }

public double getSide(){ return side; }

public double getX(){ return x; }

public double getY(){ return y; }

public void setN(int newBian){ n = newBian; }

public void setSide(double newSide){ side = newSide; }

public void setX(double newX){ x = newX; }

public void setY(double newY){ y = newY; }

public double getPerimeter(){ return n*side; }

public double getArea(){ return (n*side*side)/(4*Math.tan(Math.PI/n)); } }

18

8.11

import java.util.Scanner; public class Exercise09_11 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in); System.out.print(\ double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double d = input.nextDouble(); double e = input.nextDouble(); double f = input.nextDouble();

LinearEquation equation = new LinearEquation(a, b, c, d, e, f);

if (equation.isSolvable()) { System.out.println(\

equation.getX() + \ } else {

System.out.println(\ } } }

class LinearEquation { // Implement it private double a; private double b; private double c; private double d; private double e; private double f; public LinearEquation(double a2, double b2, double c2, double d2, double e2, double f2) { // TODO Auto-generated constructor stub a = a2; b = b2; c = c2; d = d2;

e = e2;

19

f = f2;

}

public void getA(double a2){ a = a2; }

public void getB(double b2){ b = b2; }

public void getC(double c2){ c = c2; }

public void getD(double d2){ d = d2; }

public void getE(double e2){ e = e2; }

public void getF(double f2){ f = f2; }

public boolean isSolvable(){ if(a*d-b*c != 0) return true; else return false; }

public double getX(){ return (e*d-b*f)/(a*d-b*c); }

public double getY(){ return (a*f-e*c)/(a*d-b*c); }

}

20

Chapter 9 Strings and Text I/O 第九章 字符串和文本I/O

Programming Exercises: 9.1, 9.5

9.1

import java.util.Scanner; public class EXERCISE_09_01 {

/**

* @param args */

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println(\); Scanner input = new Scanner(System.in); String num = input.nextLine(); if(isValid(num))

System.out.println(\); else

System.out.println(\);

}

public static boolean isValid(String a){

if(a.length() == 11&&

Character.isDigit(a.charAt(0)) &&

Character.isDigit(a.charAt(1)) && Character.isDigit(a.charAt(2)) && a.charAt(3) == '-' &&

Character.isDigit(a.charAt(4)) && Character.isDigit(a.charAt(5)) && a.charAt(6) == '-' &&

Character.isDigit(a.charAt(7)) && Character.isDigit(a.charAt(8)) && Character.isDigit(a.charAt(9)) && Character.isDigit(a.charAt(10))) return true; else }

return false;

}

21

9.5(Occurnences of each digit in a string)Write a method that counts the occurrences of each digit in a string using the following header: pulic static int[] count(String s)

The method counts how many times a digit appears in the string. The return value is an array of ten elements, each of which holds the count for a digit. For example, after executing int[] counts = count(\

Write a test program that prompts the user to enter a string and displays the number of occurrences of each digit in the string.

9.5 (每个数字在字符串中出现的次数)使用下列方法头编写一个方法,统计每个数字在字符串中出现的次数。

public static int[] count(String s)

这个方法统计每个数字在字符串中出现的次数,返回10个元素的数组,每个元素存储一个数字的个数。例如,执行int[] counts = count(“12203AB3”), counts[0]为1, counts[1]为1, counts[2]为2, counts[3]为2。

编写一个main方法,显示对字符串“SSN IS 343 32 5454 and ID is 434 34 4323”的统计结果。

import java.util.Scanner; public class EXERCISE_09_05 {

public static void main(String[] args) {

// TODO Auto-generated method stub Scanner input = new Scanner(System.in);

System.out.print(\); String s = input.nextLine();

int[] counts = count(s);

for(int i = 0;i

System.out.println(i+\appears \+counts[i]+((counts[i] == 1) ? \time\ : \)); }

public static int[] count(String a){ int[] counts = new int[10];

for (int i = 0; i < a.length(); i++) { if (Character.isDigit(a.charAt(i))) counts[a.charAt(i)-'0']++; }

return counts; } }

}

22

Chapter 11 Inheritance and Polymorphism 第11章 继承和多态

Programming Exercises: 11.1, 11.2, and 11.5

11.1 The Triangle class

Design a class named Triangle that extends GeometricObject. The class contains:

Three double data fields named side1,side2, and side3 with default values to 1.0 to denote three sides of the triangle.

A no-arg constructor that creates a default triangle.

A constructor that creates a triangle with the specified side1, side2,and side3. The accessor methods for all three data fields

A method named getArea() that returns the area of this triangle.

A method named getPerimetet() that returns the perimeter of this triangle. A method named toString() that returns a string to descript the triangle. The formula to compute the area of a triangle is s = (side1 + sdie2 + side3)/2; area =Math.sqrt( s*(s-side1)*(s-side2)*(s-side3))

The toString() method is implemented as follows:

Return “Triangle: side1= ”+ side1 +” side2 = ”+ sdie2 +” side3 = ”+side3;

Write a test program that creates a Triangle object with sides 10, 15, 10, set color yellow and filled true, and displays the area, perimeter, color, and whether filled or not.

1 (三角形类Triangle)扩展GeometricObject,设计名为Triangle的类,该类包括: ? 三个名为side1,side2和side3的double数据域,三角形三边的默认值为1.0; ? 一个无参构造方法创建默认的三角形;

? 指定side1,side2和side3的值,创建三角形的构造方法; ? 三个数据域的访问器方法;

? 名为getArea()的方法返回三角形的面积;

? 名为getPerimeter()的方法返回三角形的周长; ? 名为toString()的方法返回描述三角形的字符串;

计算三角形面积的公式参加练习5.19。toString()方法的执行如下: return “Triangle: side1 =” + side1 + “ side2=” +side2+ “ side3=” +side3;

画出包括Triangle和GeometricObject类的UML图,并实现这些类。编写测试程序,创建边长为1、1.5、和1的Triangle对象,设置颜色为yellow,是否填充为true。显示它的面积、周长、颜色以及是否填充。 import java.util.Scanner;

public class Exercise11_01 {

public static void main(String[] args) {

23

Scanner input = new Scanner(System.in); System.out.print(\ double side1 = input.nextDouble(); double side2 = input.nextDouble(); double side3 = input.nextDouble();

Triangle triangle = new Triangle(side1, side2, side3);

System.out.print(\ String color = input.next(); triangle.setColor(color);

System.out.print(\ boolean filled = input.nextBoolean(); triangle.setFilled(filled);

System.out.println(\ System.out.println(\ + triangle.getPerimeter()); System.out.println(triangle); } }

class Triangle extends GeometricObject { // Fill in your code double side1 = 1.0; double side2 = 1.0; double side3 = 1.0; Triangle(){ } Triangle(double side1,double side2,double side3){ this.side1 = side1; this.side2 = side2; this.side3 = side3; } public double getSide1(){ return side1; } public double getSide2(){ return side2; } public double getSide3(){ return side3; }

24

public double getArea(){ return

Math.sqrt((side1+side2+side3)/2*((side1+side2+side3)/2-side1)*((side1+side2+side3)/2-side2)*((side1+side2+side3)/2-side3)); } public double getPerimeter(){ return side1+side2+side3; } public String toString(){ return \ } }

class GeometricObject { // Copy from the book private String color = \ private boolean filled; private java.util.Date dateCreated; public GeometricObject(){ dateCreated = new java.util.Date(); } public GeometricObject(String color,boolean filled){ dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } public String getColor(){ return color; } public void setColor(String color){ this.color= color; } public boolean isFilled(){ return filled; } public void setFilled(boolean filled){ this.filled= filled; } public java.util.Date getDateCreated(){ return dateCreated;

25

} public String toString(){ return \ } } 11.2

public class Exercise11_02 {

public static void main(String[] args) { Person person = new Person(\ Student student = new Student(\ Employee employee = new Employee(\ Faculty faculty = new Faculty(\ Staff staff = new Staff(\ System.out.println(\ System.out.println(\ System.out.println(\ System.out.println(\System.out.println(\toString: \ } }

class Person{ protected String name; protected String address; protected String telephone; protected String email; Person(){ } Person(String a){ this.name = a; } public String toString() { return \ } }

class Student extends Person{ private static final int GRADE_ONE = 1; private static final int GRADE_TWO = 2; private static final int GRADE_THREE = 3; private static final int GRADE_FOUR = 4; Student(){ } Student(String s){

26

super.name = s; } public String toString() { return \ } }

class Employee extends Person{ protected String office; protected double salary; protected MyDate hireDate; protected String officeHour; protected int level; private String facName; Employee(){ } Employee(String s){ super.name = s; } public String toString() { return \ } }

class Faculty extends Employee{ Faculty(){ } Faculty(String s){ super.name = s; } public String toString() { return \ } }

class Staff extends Employee{ Staff(){ } Staff(String s){ super.name = s; } public String toString() { return \ super.name;

27

} }

class MyDate{ private int year; private int month; private int day; public String toString() { return \ } } 11.5

import java.util.ArrayList;

public class Exercise11_05{

public static void main(String[] args) {

Course course1 = new Course(\ Course course2 = new Course(\

course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\ course1.addStudent(\

course2.addStudent(\ course2.addStudent(\

System.out.println(\ + course1.getNumberOfStudents()); String[] students = course1.getStudents();

for (int i = 0; i < course1.getNumberOfStudents(); i++) System.out.print(students[i] + \

System.out.println();

System.out.print(\

28

+ course2.getNumberOfStudents());

course1.dropStudent(\

System.out.println(\ + course1.getNumberOfStudents()); students = course1.getStudents();

for (int i = 0; i < course1.getNumberOfStudents(); i++) System.out.print(students[i] + \

course1.clear();

System.out.println(\ + course1.getNumberOfStudents()); } }

class Course {

private String courseName;

private ArrayList students = new ArrayList(); private int numberOfStudents;

public Course(String courseName) { this.courseName = courseName; }

public void addStudent(String student) { // Your code here students.add(student); }

public String[] getStudents() { // Write your code here String student[] = new String[students.size()]; for(int i = 0;i

public int getNumberOfStudents() { // Write your code here return students.size(); }

public String getCourseName() { return courseName;

29

}

public void dropStudent(String student) { // Write your code here students.remove(student); }

public void clear() {

// Write your code here students.clear(); } }

Chapter 13 Exception Handling 第十三章 异常处理

Programming Exercises: 13.1, 13.3, and 13.5 (12.1, 12.3, and 12.5 in the 10th LivLab) 13.1* (NamberFormatException) Listing 9.5, Calculator.java, is a simple commandline calculator. Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals with nonnumeric operands; then Write another program without using an exception handler to achieve the same objective. Your program should display a message that informs the user of the wrong operand type before exiting

13.1 (NumberFormatException异常)程序清单8-4是一个简单的命令行计算器。注意,如果某个操作数是非数值的,程序就会中止。编写一个程序,利用异常处理方法处理非数值操作数,然后再编写一个程序,不使用异常处理方法达到同样的目的。程序退出前应该显示一条信息,通知用户发生了操作数类型错误。 public class Exercise12_01 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int result = 0; try{ switch(args[1].charAt(0)){ case '+': result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]); break; case '-': result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]); break; case '*': result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]); break; case '/': result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);

30

} System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + \ } catch(ArrayIndexOutOfBoundsException ex){ System.out.println(\ }

catch(NumberFormatException ex){ System.out.println(\ } } }

public class Exercise12_01 {

public static void main(String[] args) { String str = \

char[] c = str.toCharArray(); boolean flg = false;

for (int i = 0; i < c.length; i++) { if(!(c[i] >= 48 && c[i] <= 57)){ flg = true; break; } }

if(flg){

System.out.println(\ } } } 13.3

import java.util.Scanner; public class Exercise12_03 {

public static void main(String[] args) { // TODO Auto-generated method stub int[] array = new int[100];

for(int i = 0;i

System.out.println(\ Scanner input = new Scanner(System.in); int j = input.nextInt();

System.out.println(array[j]); }

catch(IndexOutOfBoundsException ex){

31

System.out.println(\ } } } 13.5

public class Exercise12_05 { public static void main(String[] args) { // TODO Auto-generated method stub new Exercise12_05(); } public Exercise12_05(){ try { Triangle tl=new Triangle(1.5, 2, 3); System.out.println(\ System.out.printf(\ new Triangle(1, 2, 3); } catch (IllegalTriangleException ex) { System.out.println(ex.getMessage()); } } public class IllegalTriangleException extends Exception { private double side1,side2,side3; public IllegalTriangleException() { } public IllegalTriangleException(double side1, double side2, double side3) { super(\ this.side1 = side1; this.side2 = side2; this.side3 = side3; } public double getSide1(){ return side1; } public double getSide2(){ return side2;

32

} public double getSide3(){ return side3; } } public class Triangle { double side1,side2,side3; public Triangle(double side1,double side2,double side3) throws IllegalTriangleException { if (side1 + side2 <= side3 || side1 + side3 <= side2 || side2 + side3 <= side1){ throw new IllegalTriangleException(side1,side2,side3);} else this.side1 = side1; this.side2 = side2; this.side3 = side3; } public double getArea(){ double s = (side1 + side2 + side3) / 2; return Math.sqrt(s*(s-side1)*(s-side2)*(s-side3)) ; } public double getPerimeter(){ return side1 + side2 + side3 ; } public String tostring(){ return \ } } }

Chapter 14 Abstract Classes and Interfaces第十四章 抽象类和接口

Programming Exercises: 14.1 and 14.8 (13.5 and 13.12 in the 10th LibLab)

14.1* (Enabling Ceometrfcobject comparable) Modify the Geometricobjectclass to implement the Cornparable interface, and dcfine a static max method in the Geometricobject class for finding the larger of two Ceometricobject objects, Draw the UML

33

diagram and implement the new Geometricobject class, Write a test program that uses the max method to find the larger of two circles and the larger of two rectangles.

14.1 (将GeometricObject类变成可比较的)修改GeometricObject类,以实现Comparable接口,并在该类中定义max方法,求两个GeometricObject对象中较大者。画出UML图并实现新的GeometricObject类。编写测试程序,使用max方法求两个圆中的较大者和两个矩形中的较大者。

public class Exercise13_05 { // Main method

public static void main(String[] args) { // Create two comarable circles Circle1 circle1 = new Circle1(5); Circle1 circle2 = new Circle1(4);

// Display the max circle

Circle1 circle = (Circle1)GeometricObject1.max(circle1, circle2); System.out.println(\ circle.getRadius()); System.out.println(circle); } }

abstract class GeometricObject1 implements Comparable < GeometricObject1 > { // Implement it private String color; private boolean filled; private java.util.Date dateCreated; public GeometricObject1(){ dateCreated = new java.util.Date(); } public GeometricObject1(String color,boolean filled){ dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } public String getColor(){ return color; } public void setColor(String color){ this.color = color; } public boolean isFilled(){ return filled; }

34

public void setFilled(boolean filled){ this.filled = filled; } public java.util.Date getDateCreated(){ return dateCreated; } public String toString(){ return \ } public static Comparable max(Comparable object1,Comparable object2){ if(object1.compareTo(object2)>0) return object1; else return object2; } }

// Circle.java: The circle class that extends GeometricObject class Circle1 extends GeometricObject1 { // Implement it private double radius; public Circle1(){ } public Circle1(double radius){ this.radius =radius; } public Circle1(double radius,String color,boolean filled ){ this.radius = radius; setColor(color); setFilled(filled); } public double getRadius(){ return radius; } public void setRadius(double radius){ this.radius = radius; } public double getArea(){ return radius*radius*Math.PI; } public double getPerimeter(){ return 2*radius;

35

} public void printCircle(){ System.out.println(\ \radius ); } public int compareTo(GeometricObject1 o) { // TODO Auto-generated method stub if(getArea()>((Circle1)o).getArea()) return 1; else if(getArea()<((Circle1)o).getArea()) return -1; else return 0; } } 14.8

public class Exercise13_12 {

public static void main(String[] args) { new Exercise13_12(); }

public Exercise13_12() {

GeometricObject[] a = {new Circle(5), new Circle(6), new Rectangle(2, 3), new Rectangle(2, 3)};

System.out.println(\ }

public static double sumArea(GeometricObject[] a) { // Implement it return new Circle(5).getArea()+new Circle(6).getArea()+new Rectangle(2,3).getArea()+new Rectangle(2,3).getArea(); } }

class GeometricObject{ // Implement it private String color; private boolean filled; private java.util.Date dateCreated; public GeometricObject(){ dateCreated = new java.util.Date(); } public GeometricObject(String color,boolean filled){

36

dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } public String getColor(){ return color; } public void setColor(String color){ this.color = color; } public boolean isFilled(){ return filled; } public void setFilled(boolean filled){ this.filled = filled; } public java.util.Date getDateCreated(){ return dateCreated; } public String toString(){ return \ } }

class Circle extends GeometricObject { // Implement it private double radius; public Circle(){ } public Circle(double radius){ this.radius =radius; } public Circle(double radius,String color,boolean filled ){ this.radius = radius; setColor(color); setFilled(filled); } public double getRadius(){ return radius; } public void setRadius(double radius){ this.radius = radius; }

37

public double getArea(){ return radius*radius*Math.PI; } public double getPerimeter(){ return 2*radius; } public void printCircle(){ System.out.println(\ \\ } }

class Rectangle extends GeometricObject { private double width; private double height;

public Rectangle(){ }

public Rectangle(double width,double height){ this.height = height; this.width = width; }

public Rectangle(double width,double height,String color,boolean filled){ this.height = height; this.width = width; setColor(color); setFilled(filled); }

public double getWidth(){ return width; }

public double getHeight(){ return height; }

public void setWidth(double width){ this.width = width; }

public void setHeight(double height){ this.height = height; }

public double getArea(){ return width*height; }

38

public double getPerimeter(){ return (width+height)*2; } }

39