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¸öÊý²¢ÇÒÏÔʾÆäÖÐÏ໥²»Í¬µÄÊý£¨¼´Ò»¸öÊý¶à´Î³öÏÖ£¬½öÏÔʾһ´Î£©¡£Ìáʾ£º¶ÁÈëÒ»¸öÊý£¬Èç¹ûËüÊÇÒ»¸öÐÂÊý£¬Ôò°ÑËü´æ´¢ÔÚÊý×éÖУ»Èç¹ûÊý×éÖÐÒÑÓиÃÊý£¬Ôò°ÑËü¶ªÆú¡£ÊäÈë½áÊøºó£¬Êý×éÖеÄÊý¶¼ÊDz»Í¬µÄÊý¡£ 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ÊÇÒ»¸ö¼òµ¥µÄÃüÁîÐмÆËãÆ÷¡£×¢Ò⣬Èç¹ûij¸ö²Ù×÷ÊýÊÇ·ÇÊýÖµµÄ£¬³ÌÐò¾Í»áÖÐÖ¹¡£±àдһ¸ö³ÌÐò£¬ÀûÓÃÒì³£´¦Àí·½·¨´¦Àí·ÇÊýÖµ²Ù×÷Êý£¬È»ºóÔÙ±àдһ¸ö³ÌÐò£¬²»Ê¹ÓÃÒì³£´¦Àí·½·¨´ïµ½Í¬ÑùµÄÄ¿µÄ¡£³ÌÐòÍ˳öǰӦ¸ÃÏÔʾһÌõÐÅÏ¢£¬Í¨ÖªÓû§·¢ÉúÁ˲Ù×÷ÊýÀàÐÍ´íÎó¡£ 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