Java语言程序设计(郑莉)第九章课后习题答案

合集下载

Java语言程序设计(郑莉)课后习题答案

Java语言程序设计(郑莉)课后习题答案

Java语言程序设计(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。

对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。

现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。

2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。

2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。

它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。

它的特征:抽象,封装,继承,多态。

3(无用)4.请解释类属性、实例属性及其区别。

答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。

5.请解释类方法、实例属性及其区别。

答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。

类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。

区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。

答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。

区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。

7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protecte及无修饰符. public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限). Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第九章练习题答案

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第九章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第九章练习题答案9.1public class Exercise09_01 {public static void main(String[] args) {MyRectangle myRectangle = new MyRectangle(4, 40);System.out.println("The area of a rectangle with width " +myRectangle.width + " and height " +myRectangle.height + " is " +myRectangle.getArea());System.out.println("The perimeter of a rectangle is " +myRectangle.getPerimeter());MyRectangle yourRectangle = new MyRectangle(3.5, 35.9);System.out.println("The area of a rectangle with width " +yourRectangle.width + " and height " +yourRectangle.height + " is " +yourRectangle.getArea());System.out.println("The perimeter of a rectangle is " +yourRectangle.getPerimeter());}}class MyRectangle {// Data membersdouble width = 1, height = 1;// Constructorpublic MyRectangle() {}// Constructorpublic MyRectangle(double newWidth, double newHeight) {width = newWidth;height = newHeight;}public double getArea() {return width * height;}public double getPerimeter() {return 2 * (width + height);}}9.2public class Exercise09_02 {public static void main(String[] args) {Stock stock = new Stock("SUNW", "Sun MicroSystems Inc."); stock.setPreviousClosingPrice(100);// Set current pricestock.setCurrentPrice(90);// Display stock infoSystem.out.println("Previous Closing Price: " +stock.getPreviousClosingPrice());System.out.println("Current Price: " +stock.getCurrentPrice());System.out.println("Price Change: " +stock.getChangePercent() * 100 + "%");}}class Stock {String symbol;String name;double previousClosingPrice;double currentPrice;public Stock() {}public Stock(String newSymbol, String newName) {symbol = newSymbol;name = newName;}public double getChangePercent() {return (currentPrice - previousClosingPrice) /previousClosingPrice;}public double getPreviousClosingPrice() {return previousClosingPrice;}public double getCurrentPrice() {return currentPrice;}public void setCurrentPrice(double newCurrentPrice) {currentPrice = newCurrentPrice;}public void setPreviousClosingPrice(double newPreviousClosingPrice) { previousClosingPrice = newPreviousClosingPrice;}}9.3public class Exercise09_03 {public static void main(String[] args) {Date date = new Date();int count = 1;long time = 10000;while (count <= 8) {date.setTime(time);System.out.println(date.toString());count++;time *= 10;}}}9.4public class Exercise09_04 {public static void main(String[] args) {Random random = new Random(1000);for (int i = 0; i < 50; i++)System.out.print(random.nextInt(100) + " ");}9.5public class Exercise09_05 {public static void main(String[] args) {GregorianCalendar calendar = new GregorianCalendar();System.out.println("Year is " + calendar.get(GregorianCalendar.YEAR)); System.out.println("Month is " + calendar.get(GregorianCalendar.MONTH)); System.out.println("Date is " + calendar.get(GregorianCalendar.DATE));calendar.setTimeInMillis(1234567898765L);System.out.println("Year is " + calendar.get(GregorianCalendar.YEAR)); System.out.println("Month is " + calendar.get(GregorianCalendar.MONTH)); System.out.println("Date is " + calendar.get(GregorianCalendar.DATE)); }}9.6public class Exercise09_06 {static String output = "";/** Main method */public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter yearSystem.out.print("Enter full year (i.e. 2001): ");int year = input.nextInt();// Prompt the user to enter monthSystem.out.print("Enter month in number between 1 and 12: ");int month = input.nextInt();// Print calendar for the month of the yearprintMonth(year, month);System.out.println(output);}/** Print the calendar for a month in a year */static void printMonth(int year, int month) {// Get start day of the week for the first date in the monthint startDay = getStartDay(year, month);// Get number of days in the monthint numOfDaysInMonth = getNumOfDaysInMonth(year, month);// Print headingsprintMonthTitle(year, month);// Print bodyprintMonthBody(startDay, numOfDaysInMonth);}/** Get the start day of the first day in a month */static int getStartDay(int year, int month) {// Get total number of days since 1/1/1800int startDay1800 = 3;long totalNumOfDays = getTotalNumOfDays(year, month);// Return the start dayreturn (int)((totalNumOfDays + startDay1800) % 7);}/** Get the total number of days since Jan 1, 1800 */static long getTotalNumOfDays(int year, int month) {long total = 0;// Get the total days from 1800 to year -1for (int i = 1800; i < year; i++)if (isLeapYear(i))total = total + 366;elsetotal = total + 365;// Add days from Jan to the month prior to the calendar month for (int i = 1; i < month; i++)total = total + getNumOfDaysInMonth(year, i);return total;}/** Get the number of days in a month */static int getNumOfDaysInMonth(int year, int month) {if (month == 1 || month==3 || month == 5 || month == 7 ||month == 8 || month == 10 || month == 12)return 31;if (month == 4 || month == 6 || month == 9 || month == 11)return 30;if (month == 2)if (isLeapYear(year))return 29;elsereturn 28;return 0; // If month is incorrect.}/** Determine if it is a leap year */static boolean isLeapYear(int year) {if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) return true;return false;}/** Print month body */static void printMonthBody(int startDay, int numOfDaysInMonth) { // Pad space before the first day of the monthint i = 0;for (i = 0; i < startDay; i++)output += " ";for (i = 1; i <= numOfDaysInMonth; i++) {if (i < 10)output += " " + i;elseoutput += " " + i;if ((i + startDay) % 7 == 0)output += "\n";}output += "\n";}/** Print the month title, i.e. May, 1999 */static void printMonthTitle(int year, int month) {output += " " + getMonthName(month)+ ", " + year + "\n";output += "-----------------------------\n";output += " Sun Mon Tue Wed Thu Fri Sat\n";}/** Get the English name for the month */static String getMonthName(int month) {String monthName = null;switch (month) {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;}}9.7public 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("Balance is " + account.getBalance()); System.out.println("Monthly interest is " +account.getMonthlyInterest());System.out.println("This account was created at " +account.getDateCreated());}}class Account {private int id;private double balance;private static double annualInterestRate;private java.util.Date dateCreated;public Account() {dateCreated = new java.util.Date();}public Account(int newId, double newBalance) {id = newId;balance = newBalance;dateCreated = new java.util.Date();}public int getId() {return this.id;}public double getBalance() {return balance;}public static 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 double getMonthlyInterest() {return balance * (annualInterestRate / 1200);}public java.util.Date getDateCreated() { return dateCreated;}public void withdraw(double amount) {balance -= amount;}public void deposit(double amount) {balance += amount;}}9.8public class Exercise09_08 {public static void main(String[] args) { Fan1 fan1 = new Fan1();fan1.setSpeed(Fan1.FAST);fan1.setRadius(10);fan1.setColor("yellow");fan1.setOn(true);System.out.println(fan1.toString());Fan1 fan2 = new Fan1();fan2.setSpeed(Fan1.MEDIUM);fan2.setRadius(5);fan2.setColor("blue");fan2.setOn(false);System.out.println(fan2.toString()); }}class Fan1 {public static int SLOW = 1;public static int MEDIUM = 2;public static int FAST = 3;private int speed = SLOW;private boolean on = false;private double radius = 5;private String color = "white";public Fan1() {}public int getSpeed() {return speed;}public void setSpeed(int newSpeed) {speed = newSpeed;}public boolean isOn() {return on;}public void setOn(boolean trueOrFalse) {this.on = trueOrFalse;}public double getRadius() {return radius;}public void setRadius(double newRadius) { radius = newRadius;}public String getColor() {return color;}public void setColor(String newColor) {color = newColor;}@Overridepublic String toString() {return"speed " + speed + "\n"+ "color " + color + "\n"+ "radius " + radius + "\n"+ ((on) ? "fan is on" : " fan is off"); }}public class Exercise09_09 {public static void main(String[] args) {RegularPolygon polygon1 = new RegularPolygon();RegularPolygon polygon2 = new RegularPolygon(6, 4);RegularPolygon polygon3 = new RegularPolygon(10, 4, 5.6, 7.8);System.out.println("Polygon 1 perimeter: " +polygon1.getPerimeter());System.out.println("Polygon 1 area: " + polygon1.getArea());System.out.println("Polygon 2 perimeter: " +polygon2.getPerimeter());System.out.println("Polygon 2 area: " + polygon2.getArea());System.out.println("Polygon 3 perimeter: " +polygon3.getPerimeter());System.out.println("Polygon 3 area: " + polygon3.getArea());}}class RegularPolygon {private int n = 3;private double side = 1;private double x;private double y;public RegularPolygon() {}public RegularPolygon(int number, double newSide) {n = number;side = newSide;}public RegularPolygon(int number, double newSide, double newX, double newY) {n = number;side = newSide;x = newX;y = newY;}public int getN() {return n;}public void setN(int number) {n = number;}public double getSide() {return side;}public void setSide(double newSide) {side = newSide;}public double getX() {return x;}public void setX(double newX) {x = newX;}public double getY() {return y;}public void setY(double newY) {y = newY;}public double getPerimeter() {return n * side;}public double getArea() {return n * side * side / (Math.tan(Math.PI / n) * 4); }}9.10public class Exercise09_10 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c: ");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();QuadraticEquation equation = new QuadraticEquation(a, b, c);double discriminant = equation.getDiscriminant();if (discriminant < 0) {System.out.println("The equation has no roots");}else if (discriminant == 0){System.out.println("The root is " + equation.getRoot1());}else// (discriminant >= 0){System.out.println("The roots are " + equation.getRoot1()+ " and " + equation.getRoot2());}}}class QuadraticEquation {private double a;private double b;private double c;public QuadraticEquation(double newA, double newB, double newC) {a = newA;b = newB;c = newC;}double getA() {return a;}double getB() {return b;}double getC() {return c;}double getDiscriminant() {return b * b - 4 * a * c;}double getRoot1() {if (getDiscriminant() < 0)return 0;else {return (-b + getDiscriminant()) / (2 * a);}}double getRoot2() {if (getDiscriminant() < 0)return 0;else {return (-b - getDiscriminant()) / (2 * a);}}}9.11public class Exercise09_11 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a, b, c, d, e, f: ");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("x is " +equation.getX() + " and y is " + equation.getY());}else {System.out.println("The equation has no solution");}}}class LinearEquation {private double a;private double b;private double c;private double d;private double e;private double f;public LinearEquation(double newA, double newB, double newC, double newD, double newE, double newF) {a = newA;b = newB;c = newC;d = newD;e = newE;f = newF;}double getA() {return a;}double getB() {return b;}double getC() {return c;}double getD() {return d;}double getE() {return e;}double getF() {return f;}boolean isSolvable() {return a * d - b * c != 0;}double getX() {double x = (e * d - b * f) / (a * d - b * c);return x;}double getY() {double y = (a * f - e * c) / (a * d - b * c);return y;}}9.12public class Exercise09_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the endpoints of the first line segment: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();System.out.print("Enter the endpoints of the second line segment: ");double x3 = input.nextDouble();double y3 = input.nextDouble();double x4 = input.nextDouble();double y4 = input.nextDouble();// Build a 2 by 2 linear equationdouble a = (y1 - y2);double b = (-x1 + x2);double c = (y3 - y4);double d = (-x3 + x4);double e = -y1 * (x1 - x2) + (y1 - y2) * x1;double f = -y3 * (x3 - x4) + (y3 - y4) * x3;LinearEquation equation = new LinearEquation(a, b, c, d, e, f);if (equation.isSolvable()) {System.out.println("The intersecting point is: (" +equation.getX() + ", " + equation.getY() + ")");}else {System.out.println("The two lines do not cross ");}}}9.13public class Exercise09_13 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the number of rows and columns of the array: ");int numberOfRows = input.nextInt();int numberOfColumns = input.nextInt();double[][] a = new double[numberOfRows][numberOfColumns];System.out.println("Enter the array: ");for (int i = 0; i < a.length; i++)for (int j = 0; j < a[i].length; j++)a[i][j] = input.nextDouble();Location location = locateLargest(a);System.out.println("The location of the largest element is " + location.maxValue + " at ("+ location.row + ", " + location.column + ")");}public static Location locateLargest(double[][] a) {Location location = new Location();location.maxValue = a[0][0];for (int i = 0; i < a.length; i++)for (int j = 0; j < a[i].length; j++) {if (location.maxValue < a[i][j]) {location.maxValue = a[i][j];location.row = i;location.column = j;}}return location;}}class Location {int row, column;double maxValue;}9.14public class Exercise09_14 {public static void main(String[] args) {int size = 100000;double[] list = new double[size];for (int i = 0; i < list.length; i++) {list[i] = Math.random() * list.length;}StopWatch stopWatch = new StopWatch();selectionSort(list);stopWatch.stop();System.out.println("The sort time is " + stopWatch.getElapsedTime()); }/** The method for sorting the numbers */public static void selectionSort(double[] list) {for (int i = 0; i < list.length - 1; i++) {// Find the minimum in the list[i..list.length-1]double currentMin = list[i];int currentMinIndex = i;for (int j = i + 1; j < list.length; j++) {if (currentMin > list[j]) {currentMin = list[j];currentMinIndex = j;}}// Swap list[i] with list[currentMinIndex] if necessary;if (currentMinIndex != i) {list[currentMinIndex] = list[i];list[i] = currentMin;}}}}class StopWatch {private long startTime = System.currentTimeMillis(); private long endTime = startTime;public StopWatch() {}public void start() {startTime = System.currentTimeMillis();}public void stop() {endTime = System.currentTimeMillis();}public long getElapsedTime() {return endTime - startTime;}}。

Java程序设计课后练习答案

Java程序设计课后练习答案

《J a v a程序设计》课后练习答案第一章Java概述一、选择题1.( A )是在Dos命令提示符下编译Java程序的命令,( B )是运行Java程序的命令。

A.javacB.javaC.javadocD.javaw2.( D )不是Java程序中有效的注释符号。

A.//B.C.D.3.(A.B.C.D.4.JavaA.B.C.D.5.JavaA.1、JavaJava(JVM)Java以下图展示了Java程序从编译到最后运行的完整过程。

2、简述Java语言的特点Java具有以下特点:1)、简单性Java语言的语法规则和C语言非常相似,只有很少一部分不同于C语言,并且Java还舍弃了C语言中复杂的数据类型(如:指针和结构体),因此很容易入门和掌握。

2)、可靠性和安全性Java从源代码到最终运行经历了一次编译和一次解释,每次都有进行检查,比其它只进行一次编译检查的编程语言具有更高的可靠性和安全性。

3)、面向对象Java是一种完全面向的编程语言,因此它具有面向对象编程语言都拥有的封装、继承和多态三大特点。

4)、平台无关和解释执行Java语言的一个非常重要的特点就是平台无关性。

它是指用Java编写的应用程序编译后不用修改就可在不同的操作系统平台上运行。

Java之所以能平台无关,主要是依靠Java虚拟机(JVM)来实现的。

Java编译器将Java源代码文件编译后生成字节码文件(一种与操作系统无关的二进制文件)5)、6)、Java来。

1、/****/}}第二章Java语法基础一、选择题1.下面哪个单词是Java语言的关键字( B )?A. DoubleB. thisC. stringD. bool2.下面属于Java关键字的是( D )。

A. NULLB. IFC. DoD. goto3.在启动Java应用程序时可以通过main( )方法一次性地传递多个参数。

如果传递的参数有多个,可以用空格将这些参数分割;如果某一个参数本身包含空格,可以使用( B )把整个参数引起来。

java语言程序设计课后习题答案解析

java语言程序设计课后习题答案解析

习题23.使用“= =”对相同内容的字符串进行比较,看会产生什么样的结果。

答:首先创建一个字符串变量有两种方式:String str = new String("abc");String str = "abc";使用“= =”会因为创建的形式不同而产生不同的结果:String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1= =str2); //falseString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1= =str2); //false因此自符串如果是对内容进行比较,使用equals方法比较可靠。

String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1.equals(str2)); //trueString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1.equals(str2)); //true5.编写一个程序,把变量n的初始值设置为1678,然后利用除法运算和取余运算把变量的每位数字都提出来并打印,输出结果为:n=1678。

Java程序设计教程 第九章

Java程序设计教程 第九章

9.1.2ava中,每个线程从创建到消亡为一个生 Java中,每个线程从创建到消亡为一个生 存周期,它将经历四个状态: (1)新建状态(New Thread Status )新建状态(New (2)可执行状态(Runnable) )可执行状态(Runnable) (3)阻塞状态(Blocked) )阻塞状态(Blocked) (4)消亡状态(Dead thread) )消亡状态(Dead thread)
9.1.2 线程的控制
4. 终止一个线程 在程序中不能任意终止一个线程,否则可能 造成严重的线程安全问题.一个线程的终止 必须靠run()方法的正常返回.当一个线程从 必须靠run()方法的正常返回.当一个线程从 run()方法返回后,它就进入消亡状态,再也 run()方法返回后,它就进入消亡状态,再也 不能被运行了.结束run()方法还有另一种途 不能被运行了.结束run()方法还有另一种途 径,那就是在run()方法中抛出了异常,如果 径,那就是在run()方法中抛出了异常,如果 这些异常没有被捕获,JVM将会终止该线程. 这些异常没有被捕获,JVM将会终止该线程.
9.1.1 线程的概念
与程序的顺序执行相对的是程序的并发执行, 即一组逻辑上互相独立的程序或程序段在执 行过程中,其执行时间在客观上互相重叠. 程序的并发执行可以分成两种情况:一种是 多道程序系统中多道程序的并发执行,此种 情况下实际上是宏观上(程序级)同时进行, 微观上(指令级)顺序执行的;另一种是在 某道程序段的几个程序片段中,包含着一部 分可以同时执行或顺序颠倒执行的代码.程 序的并发执行是实现多线程技术的基础.
9.1.1 线程的概念
线程与进程类似,是一段完成特定功能的代 码.它是程序中单个顺序的控制流,也是一 个进程内的基本调度单位.线程和进程一样 拥有独立的执行控制,并由操作系统负责调 度.同一进程可以包含多个线程,这些线程 共享属于该进程的一块内存空间和一组系统 资源;而线程自身的数据通常只有微处理器 的寄存器数据,以及一个供程序执行时使用 的堆栈.系统在产生一个线程,或者在各个 线程之间切换时,负担要比进程小得多.此 外,由于线程只是在单个进程的作用域内活 动,所以线程间的通信也比进程简单.线程 的实现要依靠操作系统,现代操作系统一般 都支持线程技术.

JAVA课后习题答案

JAVA课后习题答案

JAVA课后习题答案第⼀章Java语⾔概述2.“java编译器将源⽂件编译为的字节码⽂件是机器码”这句话正确吗?答:不正确3.java应⽤程序的主类必须含有怎样的⽅法?答:含有main⽅法4。

“java应⽤程序必须有⼀个类是public类”这句话正确吗?答;不正确,只能有⼀个public类5。

“java Applet程序的主类必须是public类”这句话正确吗?答:正确,因为java Applet主类必须是Applet类的⼦类并且是public的类6。

请叙述java源程序的命名规则。

答:与public的类同名。

7。

源⽂件⽣成的字节码⽂件在运⾏时都加载到内存中吗?答:⾮也,动态随需要运⾏才加载。

8.⾯向对象的程序设计语⾔有那些基本特征?答:封装;继承;多态性。

9.在Java程序中有多个类⽂件时,⽤Java命令应该运⾏那个类?答:具有main⽅法的类第⼆章基本数据类型和数组4。

下列哪些语句是错的?Int x=120;Byte b=120;b=x;答:B=x;错应为b=(byte)x5。

下列哪些语句是错的?答:y=d;错,应y=(float)d6。

下列两个语句是等价的吗?Char x=97;Char x=…a?;答:是等价的。

7。

下列system.out.printf语句输出结果是什么?Int a=97;Byte b1=(byte)128;Byte b2=(byte)(-129);System.out.printf(“%c,%d,%d”,a,b1,b2);如果输出语句改为:System.out.printf(“%d,%d,%d”,a,b1,b2);输出什么?答:输出a ,-128,127修改后输出97,-128,1278.数组是基本数据类型吗?怎样获取数组的长度?答:不是基本数据类型,是复合数据类型。

可以通过:数组名.length的⽅法获得数组长度9。

假设有两个int类型数组:Int[] a=new int[10];Int[] b=new int[8];b=a;A[0]=100;B[0]的值⼀定是100吗?答;⼀定,因为a数组与b数组引⽤相同。

JAVA第9章第10章课后习题答案

JAVA第9章第10章课后习题答案

第9章多线程4、C5、D6、package cn.ntu.zhanbin;public class ThreadOutput implements Runnable {static ThreadOutput to = new ThreadOutput();public static void main(String[] args) {//创建两个线程Thread t1 = new Thread(new ThreadOutput());Thread t2 = new Thread(new ThreadOutput());t1.start();t2.start();}public void run() {synchronized (to) {to.print();}}void print() {for (int i = 0; i < 6; i++) {System.out.print(10 + i);if (i < 5) {System.out.print(",");}try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("");}}--------------------------------------------------------------------- 8、package cn.ntu.zhanbin;public class ThreadAlphabet extends Thread {public static void main(String[] args) {//创建3个线程ThreadAlphabet ta1 = new ThreadAlphabet("线程1:");ThreadAlphabet ta2 = new ThreadAlphabet("线程2:");ThreadAlphabet ta3 = new ThreadAlphabet("线程3:");ta1.start();ta2.start();ta3.start();}ThreadAlphabet(String name) {super(name);//调用父类的构造函数}public void run() {//获取当前线程名String name = Thread.currentThread().getName();//输出for (int i = 0; i < 26; i++) {System.out.println(name + (char) (i + 65));try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}}}--------------------------------------------------------------------- 9、package cn.ntu.zhanbin;public class PrintOdds implements Runnable {private int bound;//创建一个静态PrintOdds对象,并设置边界范围为20static PrintOdds po = new PrintOdds(20);public PrintOdds(int b) {bound = b;}public void print() {for (int i = 1; i < bound; i+=2) {System.out.println(i);}}public void run() {po.print();}public static void main(String[] args) {Thread t = new Thread(po);t.start();}}第10章数据库编程说明:课本中连接数据库和关闭数据库的操作都是调用的P201的例10-1的ConnectionManager,而书中的类只写了getConnection()方法,各个关闭操作的方法均未给出。

java习题及答案第9章 习题参考答案

java习题及答案第9章 习题参考答案

第9章习题解答1.与输入/输出有关的流类有哪些?答:与输入/输出有关的流类主要有InputStream、OutputStream和Reader、Writer类及其子类。

除此以外,与流有关的类还有File类、FileDescriptor类、StreamTokenizer类和RandomAccessFile类。

2.字节流与字符流之间有哪些区别?答:字节流是面向字节的流,流中的数据以8位字节为单位进行读写,是抽象类InputStream和OutputStream的子类,通常用于读写二进制数据,如图像和声音。

字符流是面向字符的流,流中的数据以16位字符(Unicode字符)为单位进行读写,是抽象类Reader和Writer的子类,通常用于字符数据的处理。

3.什么是节点流?什么是处理流或过滤流?分别在什么场合使用?答:一个流有两个端点。

一个端点是程序;另一个端点可以是特定的外部设备(如键盘、显示器、已连接的网络等)和磁盘文件,甚至是一块内存区域(统称为节点),也可以是一个已存在流的目的端。

流的一端是程序,另一端是节点的流,称为节点流。

节点流是一种最基本的流。

以其它已经存在的流作为一个端点的流,称为处理流。

处理流又称过滤流,是对已存在的节点流或其它处理流的进一步处理。

对节点流中的数据只能按字节或字符读写。

当读写的数据不是单个字节或字符,而是一个数据块或字符串等时,就要使用处理流或过滤流。

4.标准流对象有哪些?它们是哪个类的对象?答:标准流对象有3个,它们是:System.in、System.out和System.err。

System.in 是InputStream类对象,System.out和System.err是PrintStream类对象。

5.顺序读写与随机读写的特点分别是什么?答:所谓顺序读写是指在读写流中的数据时只能按顺序进行。

换言之,在读取流中的第n个字节或字符时,必须已经读取了流中的前n-1个字节或字符;同样,在写入了流中n-1个字节或字符后,才能写入第n个字节或字符。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Java语言程序设计第九章课后习题答案1.编写一个程序,该程序绘制一个5×9的网络,使用drawLine方法。

//NetWork类import java.awt.Graphics;import javax.swing.JFrame;public class NetWork extends JFrame{public NetWork(){// 设置窗体大小this.setSize(130, 130);//设置窗体大小不可改变this.setResizable(false);// 设置默认关闭方式,关闭窗体的同时结束程序this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 将窗体显示出来this.setVisible(true);}//横纵格之间都间隔10像素,起点在(20,40)public void paint(Graphics g){//绘制横向线for(int i=0;i<=5;i++){g.drawLine(20, 40+i*10, 110, 40+i*10);}//绘制纵向线for(int i=0;i<=9;i++){g.drawLine(20+i*10, 40, 20+i*10, 90);}}}//test9_1类public class test9_1 {public static void main(String[] args){new NetWork();}}运行结果:2.编写一个程序,该程序以不同的颜色随机产生三角形,每个三角形用不同的颜色进行填充。

//Triangle类import java.awt.Color;import java.awt.Graphics;import java.util.Random;import javax.swing.JFrame;public class Triangle extends JFrame{Random rnd = new Random();//这里定义4个三角形int[][] x=new int[4][3];int[][] y=new int[4][3];int[][] color=new int[4][3];public Triangle(){for(int i=0;i<4;i++){for(int j=0;j<3;j++){color[i][j]=rnd.nextInt(255);x[i][j]=rnd.nextInt(i*100+100);y[i][j]=rnd.nextInt(i*100+100)+50;//加50像素是为了避免顶到窗体上沿}}//窗体标题this.setTitle("随机三角形");//窗体大小this.setSize(500,500);//窗体大小不可变this.setResizable(false);//关闭窗体的同时结束程序this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//显示窗体this.setVisible(true);}public void paint(Graphics g){for(int i=0;i<4;i++){g.setColor(new Color(color[i][0],color[i][1],color[i][2]));g.fillPolygon(x[i], y[i], 3);}}}//test9_2public class test9_2 {public static void main(String[] args){new Triangle();}}运行结果:3.编写一个Applet,该程序请求用户输入圆的半径,然后显示该圆的直径、周长和面积。

//test9_3import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class test9_3 extends JApplet {//声明5个标签private JLabel jLabel1;private JLabel jLabel2;private JLabel jLabel3;private JLabel jLabel4;private JLabel jLabel5;//1个单行文本private JTextField textOfRadius;//2个按钮private JButton jButton1;private JButton jButton2;//初始化public void init() {try {java.awt.EventQueue.invokeAndWait(new Runnable() {public void run() {initComponents();}});} catch (Exception ex) {ex.printStackTrace();}}private void initComponents() {//声明8个组件jLabel1 = new JLabel("输入圆的半径:", SwingConstants.CENTER);jLabel2 = new JLabel("圆的周长:", SwingConstants.CENTER);jLabel3 = new JLabel("", SwingConstants.CENTER);jLabel4 = new JLabel("圆的面积:", SwingConstants.CENTER);jLabel5 = new JLabel("", SwingConstants.CENTER);textOfRadius = new JTextField("半径");jButton1 = new JButton("计算");jButton2 = new JButton("退出");//按钮添加监听器jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) {jButton1ActionPerformed(evt);}});//按钮添加监听器jButton2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) {jButton2ActionPerformed(evt);}});//声明定义内容面板,并且设置其布局格式为:4行2列格子Container c = getContentPane();c.setLayout(new GridLayout(4, 2));//将8个组件加入到内容面板c.add(jLabel1);c.add(textOfRadius);c.add(jLabel2);c.add(jLabel3);c.add(jLabel4);c.add(jLabel5);c.add(jButton1);c.add(jButton2);}// 求周长方法private String Round(double a) {double perimeter = a * 2 * 3.14;String s = new String(String.valueOf(perimeter));return s;}// 求面积方法private String Area(double a) {double area = a * a * 3.14;String s = new String(String.valueOf(area));return s;}//点击“计算”按钮jButton1触发的方法private void jButton1ActionPerformed(ActionEvent evt) {//捕获单文本输入非数字的异常try {String s = textOfRadius.getText();//获得单文本字符double a = Double.valueOf(s).floatValue();//字符转化为双精度jLabel3.setText(Round(a));//标签内容为周长jLabel5.setText(Area(a));//标签内容为面积} catch (NumberFormatException r) {//单文本为非数字弹出提示“输入错误”框JOptionPane.showMessageDialog(this, "请输入数字类型", "输入错误",JOptionPane.WARNING_MESSAGE);textOfRadius.setText("");}}//点击“退出”按钮jButton2触发的方法public void jButton2ActionPerformed(ActionEvent evt) {System.exit(0);}}运行结果:编译text9_3.java产生字节码文件test9_3.class,接下来需要编写一个HTML文件text9_3.html来嵌入text9_3.class,代码如下:<html><applet code="test9_3.class"></applet></html>将test9_3.html文件和test9_3.class文件放在同一个目录下,在浏览器中打开这个test9_3.html文件,实现的效果如下:4.编写一个Applet,向其输入五个数,然后以条形图(bar graph)的形式来表示这些数。

5.编写一个绘制圆形的程序,当鼠标在绘制区域中单击时,该正方形的左上角顶点应准确的跟随鼠标光标移动,重绘该圆形。

//MyJFrame类import java.awt.Graphics;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.JFrame;public class MyJFrame extends JFrame implements MouseListener{ int x=50;int y=50;int radius=50;public MyJFrame(){this.setTitle("绘制圆形");this.setSize(200,200);this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.addMouseListener(this);this.setVisible(true);}public void paint(Graphics g){g.drawOval(x, y, radius, radius);}public void mouseClicked(MouseEvent e) {// TODO Auto-generated method stubthis.x=e.getX();this.y=e.getY();this.repaint();System.out.println("x: " + e.getX() + "\ny: " + e.getY());}public void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}public void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}public void mousePressed(MouseEvent e) {// TODO Auto-generated method stub}public void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}}//test9_5public class test9_3 {public static void main(String[] args){new MyJFrame();}}运行结果:6.编写一个“猜数”程序:该程序随机在1到100的范围内选择一个供用户猜测的整数,然后改程序显示提示信息,要求用户输入一个1到100之间的整数,根据输入偏大、偏小、正确,程序将显示不同的图标。

相关文档
最新文档