自考JAVA语言程序设计(一)课后习题答案和源代码(第九章)演示教学
- 格式:doc
- 大小:382.50 KB
- 文档页数:13
全国2012年10月自考Java语言程序设计(一)试题课程代码:04747请考生按规定用笔将所有试题的答案涂、写在答题纸上。
选择题部分注意事项:1. 答题前,考生务必将自己的考试课程名称、姓名、准考证号用黑色字迹的签字笔或钢笔填写在答题纸规定的位置上。
2. 每小题选出答案后,用2B铅笔把答题纸上对应题目的答案标号涂黑。
如需改动,用橡皮擦干净后,再选涂其他答案标号。
不能答在试题卷上。
一、单项选择题(本大题共10小题,每小题1分,共10分)在每小题列出的四个备选项中只有一个是符合题目要求的,请将其选出并将“答题纸’’的相应代码涂黑。
错涂、多涂或未涂均无分。
1. Java语言中,int类型占用的二进制位数是A. 8位B. 16位C. 32位D. 64位2. 以下关于Java语句的说法正确的是A. continue语句必须出现在多路按值选择结构或循环结构中B. return语句可以出现在方法体的外面C. 编译系统会把单独的分号看成是空语句D. break语句的作用是提早结束当前轮次循环3. 不能..被再继承的类是A. final类B. abstract类C. public类D. 用户自定义类4. 已知String s="ABCDEFGHIJABC",以下说法错误..的是A. s.indexOf("C")等于2B. s.indexOf("EFG",2)等于4C. s.indexOf("A",7)等于10D. s.indexOf("D",4)等于35. 以下Swing提供的GUI组件类和容器类中,不属于...顶层容器的是A. JFrameB. JAppletC. JDialogD. JMenu6. 以下不是..JDialog类构造方法的是A. JDialog( )B. JDialog(boolean b)C. JDialog(JFrame f, String s)D. JDialog(JFrame f, String s, boolean b)7. 以下不属于...文字字型要素的是A. 字体B. 风格C. 字号D. 颜色8. 阻塞状态的线程在消除引起阻塞的原因后,会转入A. 死亡状态B. 开始状态C. 就绪状态D. 运行状态9. 字符流数据是A. 8位的ASCII字符B. 16位的Unicode字符C. 任意字符数据D. 任意二进制数据10. 以下方法中,可以执行SQL查询语句的是A. executeQuery( )B. executeUpdate( )C. executeSQL( )D. executeFind( )非选择题部分注意事项:用黑色字迹的签字笔或钢笔将答案写在答题纸上,不能答在试题卷上。
《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;}}。
全国2010年1月自考Java 语言程序设计(一)试题 1 全国2010年1月自考Java 语言程序设计(一)试题课程代码:04747一、单项选择题(本大题共10小题,每小题1分,共10分)在每小题列出的四个备选项中只有一个是符合题目要求的,请将其代码填写在题后的括号内。
错选、多选或未 选均无分。
1.在下述字符串中,不属于...Java 语言关键字的是 ( )A .floatB .newC .javaD .return2.Java 语言中数值数据的类型能自动转换,按照从左到右的转换次序为 ( )A . byte →int →short →long →float →doubleB . byte →short →int →long →float →doubleC . byte →short →int →float →long →doubleD . short →byte →int →long →float →double3.在以下供选择的概念中,不属于...面向对象语言概念的是 ( ) A .消息B .模块C .继承D .多态性4.在下述Java 语言语句中,错误..的创建数组的方法是 ( ) A .int intArray [ ]; intArray=new int[5];B .int intArray [ ]=new int[5];C .int [ ] intArray ={1,2,3,4,5};D .int intArray [5]={1,2,3,4.5};5.在Swing 中,它的子类能用来创建框架窗口的类是 ( )A .JWindowB .JFrameC .JDialogD .JApplet6.MouseListener 接口不能..处理的鼠标事件是 ( ) A .按下鼠标左键B .点击鼠标右键C .鼠标进入D .鼠标移动7.以下不属于...文字字型要素的是 ( )全国2010年1月自考Java 语言程序设计(一)试题 2A .颜色B .字体C .风格D .字号8.在以下四个供选的整数中,能作为线程最高优先级的整数是 ( )A .0B .1C .10D .119.Java 语言可以用javax.swing 包中的类JFileChooser 来实现打开和保存文件对话框。
第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()方法,各个关闭操作的方法均未给出。
第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】ﻫ题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月得兔子总数为多少?ﻫ//这就是一个菲波拉契数列问题public class lianxi01{ﻫpublic staticvoid main(String[]args) {System、out、println("第1个月得兔子对数: 1”);System、out、println("第2个月得兔子对数: 1");intf1= 1,f2 =1,f,M=24;ﻫfor(int i=3;i〈=M; i++){ﻫf= f2;f2= f1+f2;ﻫf1 = f;System、out、println("第”+ i+”个月得兔子对数:"+f2);}ﻫ}ﻫ}【程序2】题目:判断101-200之间有多少个素数,并输出所有素数。
ﻫ程序分析:判断素数得方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不就是素数,反之就是素数。
ﻫpublicclass lianxi02 {ﻫpublic staticvoidmain(String[]args){ﻫint count = 0;ﻫfor(int i=101; i〈200;i+=2){ booleanb=false;for(int j=2; j〈=Math、sqrt(i);j++)ﻫ{ﻫif(i % j == 0){ b = false;break;}ﻫelse { b =true;}ﻫ}ﻫif(b== true) {coun t++;System、out、println(i );}}ﻫSystem、out、println( "素数个数就是: " + count);}}【程序3】ﻫ题目:打印出所有得"水仙花数”,所谓”水仙花数"就是指一个三位数,其各位数字立方与等于该数本身.例如:153就是一个"水仙花数",因为153=1得三次方+5得三次方+3得三次方。
Java语言程序设计(一)课后习题第九章(附答案)九、Java Applet概述1.下列方法中,哪一个不是Applet的基本方法()A、init()B、run()C、stop()D、start()2.在Java中判定Applet的来源的方法有()A、getcodebase()B、get文档base()C、getCodeBase()D、get文档Bade()3.下面关于Applet的说法正确的是A、Applet也需要main方法B、Applet必需继承自javawt.AppletC、Applet能拜候本地文件D、Applet程序不需要编译4.Applet类的直接父类是( )ponent类B.Container类C.Frame类D.Panel类5.判断:一个Applet编译后的类名是Test.class,运行此小程序的命令是Java Test。
()6.编写同时具有Applet与Application的特征的程序。
具体方法是:作为Application要定义main()方法,并且把main()方法所在的类定义一个类。
为使该程序成为一个Applet,main()方法所在的这个类必需继承Applet类或JApplet类。
7.在第一次加载Applet时,默认最先执行的方法是________。
8.调用________方法可以把HTML网页中的参数传递给Applet。
9.使用________方法可以从Web站点上下载声音,并调用play()方法和loop()方法播放它们。
10.Java程序可以通过调用哪个方法完成重画任务?参考答案1.B2.C D3. C4. C5. false6. 主7.init()8.getParameter()9.getAudioClip()10.repaint()。
第九章2.一个文本,一个按钮。
在文本区中输入数据,点击按钮,将文本内容输出到文件。
文件通过文件保存对话框制定。
程序运行结果:保存文件的源文件: SaveFile.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;/*** 9.2 一个文本,一个按钮。
<BR>* 在文本区中输入数据,点击按钮,将文本内容输出到文件。
<BR>* 文件通过文件保存对话框制定。
<BR>* @author黎明你好*/public class SaveFile extends JFrame implements ActionListener{private static final long serialVersionUID = 1L;// 序列化时为了保持版本的兼容性private JFileChooser fileChooser;// 文件选择对话框private JPanel northPanel;// 布局用的private JButton saveFileButton;// 保存按钮private JLabel label;// 用来显示文件的绝对路径private JTextArea textArea;// 文本框public SaveFile(){super("第九章,第二题- 保存文件");label = new JLabel(" ");fileChooser = new JFileChooser();northPanel = new JPanel();saveFileButton = new JButton("保存到文件");textArea = new JTextArea();textArea.setLineWrap(true);saveFileButton.addActionListener(this);northPanel.add(saveFileButton);this.add(northPanel, BorderLayout.NORTH);this.add(new JScrollPane(textArea), BorderLayout.CENTER);this.add(label, BorderLayout.SOUTH);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setBounds(50, 50, 500, 500);this.setVisible(true);this.validate();}public void actionPerformed(ActionEvent e) // 监听器方法{if (e.getSource() == saveFileButton){int message = fileChooser.showSaveDialog(this);if (message == JFileChooser.APPROVE_OPTION){File file = fileChooser.getSelectedFile();label.setText("保存到:" + file.getAbsolutePath());// 在label上显示这个文件的绝对路径this.setTitle(file.getName());// 设置JFrame的title为文件的名字saveFile(file);}else{label.setText("没有文件被选中");}}}/*** 把文本区上的内容保存到指定文件上* @param f - 保存到的文件对象*/public void saveFile(File f){try{FileWriter file = new FileWriter(f);BufferedWriter out = new BufferedWriter(file);out.write(textArea.getText(), 0, textArea.getText().length());out.close();}catch( Exception e ){label.setText("写文件发生错误");}}public static void main(String[] args){new SaveFile();}}3.在一个文件中,每行存的是整数,各行整数个数不等,要求读这个文件,然后计算每行整数的和,并存到另一个文件中。
Chapter9Strings and Text I/O1.s1==s2=>trues2==s3=>falses1.equals(s2)=>trues2.equals(s3)=>truepareTo(s2)=>0pareTo(s3)=>0s1==s4=>trues1.charAt(0)=>Ws1.indexOf('j')=>-1s1.indexOf("to")=>8stIndexOf('a')=>14stIndexOf("o",15)=>9s1.length()=>16s1.substring(5)=>me to Javas1.substring(5,11)=>me tos1.startsWith("Wel")=>trues1.endsWith("Java")=>trues1.toLowerCase()=>welcome to javas1.toUpperCase()=>WELCOME TO JAVA"Welcome".trim()=>Welcomes1.replace('o','T')=>WelcTme tT Javas1.replaceAll("o","T")=>WelcTme tT Javas1.replaceFirst("o","T")=>WelcTme tT Javas1.toCharArray()returns an array of characters consisting of W,e,l,c,o,m,e,,t,o,,J,a,v,a (Note that none of the operation causes the contents of a string to change)2.String s=new String("new string");Answer:CorrectString s3=s1+s2;Answer:CorrectString s3=s1-s2;Answer:Incorrects1==s2Answer:Corrects1>=s2Answer:IncorrectpareTo(s2);Answer:Correctint i=s1.length();Answer:Correctchar c=s1(0);Answer:Incorrectchar c=s1.charAt(s1.length());Answer:Incorrect:it's out of bounds,even if the preceding problem is fixed.3.The output isWelcome to JavaWelcabcme tabc JavaHint:No method in the String class can change the content of the string.String is an immutable class.4.∙Check whether s1is equal to s2and assign the result to a Boolean variable isEqual.boolean isEqual=s1.equals(s2);∙Check whether s1is equal to s2ignoring case and assign the result to a Boolean variable isEqual.boolean isEqual=s1.equalsIgnoreCase(s2);∙Compare s1with s2and assign the result to an int variable x.int x=pareTo(s2);∙Compare s1with s2ignoring case and assign the result to an int variable x.int x=pareToIgnoreCase(s2);∙Check whether s1has prefix"AAA"and assign the result to a Boolean variable b.boolean b=s1.startsWith("AAA");∙Check whether s1has suffix"AAA"and assign the result to a Boolean variable b.boolean b=s1.endsWith("AAA");∙Assign the length of s1to an int variable x.int x=s1.length();∙Assign the first character of s1to a char variable x. char x=s1.charAt(0);∙Create a new string s3that combines s1with s2.String s3=s1+s2;∙Create a substring of s1starting from index 1.String s3=s1.substring(1);∙Create a substring of s1from index1to index 4. String s3=s1.substring(1,5);∙Create a new string s3that converts s1to lowercase. String s3=s1.lowercase();∙Create a new string s3that converts s1to uppercase. String s3=s1.uppercase();∙Create a new string s3that trims blank spaces on both ends of s1.String s3=s1.trim();∙Replace all occurrence of character e with E in s1and assign the new string to s3.String s3=s1.replaceAll(‘e’,‘E’);∙Split"Welcome to Java and HTML"into an array tokens using delimited by a space.String[]tokens="Welcome to Java and HTML".split(‘‘);∙Assign the index of the first occurrence of charactere in s1to an int variable x.int x=s1.indexOf(‘e‘);Assign the index of the last occurrence of string abc in s1to an int variable x.int x=stIndexOf(“abc”);5.No.6.0.e the overloaded static valueOf method in the String class.8.The text is declared in Line2as a data field,but redeclared in Line5as a localvariable.The local variable is assigned with the string passed to the constructor,but the data field is still null.In Line10,test.text is null,which causesNullPointerException when invoking the toLowerCase()method.9.The constructor is declared incorrectly.It should not have void.10.A lowercase letter is between‘a’and‘z’.You can use the staticisLowerCase(char)method in the Character class to test if a character is inlowercase.An uppercase letter is between‘A’and‘Z’.You can use the staticisUpperCase(char)method in the Character class to test if a character is inuppercase.11.An alphanumeric character is between‘0’and‘9’,or‘A’and‘Z’,or‘a’and‘z’.You can use the static isLetterOrDigit(char ch)method in the Character class totest if a character is a digit or a letter.12.The StringBuilder class,introduced in JDK1.5,is similar to StringBuffer exceptthat the update methods in StringBuffer are synchronized.e the StringBuilder’s constructor to create a string buffer for a string,and usethe toString method in StringBuilder class to return a string from a StringBuilder.14.StringBuilder sb=new StringBuilder(s);sb.reverse();s=sb.toString();15.StringBuilder sb=new StringBuilder(s);sb.delete(4,10);s=sb.toString();16.Both string and string buffer use arrays to hold characters.The array in a string isfixed once a string is created.The array in a string buffer may change if the buffer capacity is changed.To accommodate the change,a new array is created.17.(1)Java is fun(2)JavaHTML(3)Jais funva(4)JHTMLava(5)v(6)4(7)Jav(8)Ja(9)avaJ(10)JComputera(11)av(12)va18.The output isJavaJava and HTMLNOTE:Inside the method,the statement s=s+"and HTML"creates a new String objects,which is different from the original String object passed to the change(s,buffer)method.The original String object has not been changed.Therefore,the printoutfrom the original string is Java.Inside the method,the content of the StringBuilder object is changed to Java andHTML.Therefore,the printout from buffer is Java and HTML.19.public static void main(String[]args)can be replaced bypublic static void main(String args[])public static void main(String[]x)public static void main(String x[])but notstatic void main(String x[])because it is not public.20.(1)Number of strings is4Ihaveadream(2)Number of strings is1123(3)Number of strings is0(4)Number of strings is1*(5)Number of strings is(the number of files and directory from where the commandis executed)Displays all files and directory names in the directory where the command isexecuted.21.The\is a special character.It should be written as\\in Java using the Escapesequence.e exists()in the File class to check whether a file e delete()in the Fileclass to delete this e renameTo(File)to rename the name for this file.Youcannot find the file size using the File class.23.No.The File class can be used to obtain file properties and manipulate files,butcannot perform I/O.24.To create a PrintWriter for a file,use new PrintWriter(filename).This statementmay throw an exception.Java forces you to write the code to deal with exceptions.One way to deal with it is to declare throws Exception in the method declaration.If the close()method is not invoked,the data may not be saved properly.25.The contents of the file temp.txt is:amount is32.320000 3.232000e+01amount is32.3200 3.2320e+01falseJava26.To create a Scanner for a file,use new Scanner(new File(filename)).This statementmay throw an exception.Java forces you to write the code to deal with exceptions.One way to deal with it is to declare throws Exception in the method declaration.If the close()method is not invoked,the problem will run fine.But it is a goodpractice to close the file to release the resource on the file.27.If you attempt to create a Scanner for a nonexistent file,an exception will occur.Ifyou attempt to create a Formatter for an existing file,the contents of the existingfile will be gone.28.No.The line separator on Windows is\r\n.29.intValue contains45.doubleValue contains57.8,andline contains'','7','8','9'.30.intValue contains45.doubleValue contains57.8,andline is empty.。
第九章2.一个文本,一个按钮。
在文本区中输入数据,点击按钮,将文本内容输出到文件。
文件通过文件保存对话框制定。
程序运行结果:保存文件的源文件: SaveFile.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;/***9.2一个文本,一个按钮。
<BR>*在文本区中输入数据,点击按钮,将文本内容输出到文件。
<BR>*文件通过文件保存对话框制定。
<BR>*@author黎明你好*/public class SaveFile extends JFrame implements ActionListener{private static final long serialVersionUID = 1L;// 序列化时为了保持版本的兼容性private JFileChooser fileChooser;// 文件选择对话框private JPanel northPanel;// 布局用的private JButton saveFileButton;// 保存按钮private JLabel label;// 用来显示文件的绝对路径private JTextArea textArea;// 文本框public SaveFile(){super("第九章,第二题 - 保存文件");label = new JLabel(" ");fileChooser = new JFileChooser();northPanel = new JPanel();saveFileButton = new JButton("保存到文件");textArea = new JTextArea();textArea.setLineWrap(true);saveFileButton.addActionListener(this);northPanel.add(saveFileButton);this.add(northPanel, BorderLayout.NORTH);this.add(new JScrollPane(textArea), BorderLayout.CENTER);this.add(label, BorderLayout.SOUTH);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setBounds(50, 50, 500, 500);this.setVisible(true);this.validate();}public void actionPerformed(ActionEvent e) // 监听器方法{if (e.getSource() == saveFileButton){int message = fileChooser.showSaveDialog(this);if (message == JFileChooser.APPROVE_OPTION){File file = fileChooser.getSelectedFile();label.setText("保存到:" + file.getAbsolutePath());// 在label上显示这个文件的绝对路径this.setTitle(file.getName());// 设置JFrame的title为文件的名字saveFile(file);}else{label.setText("没有文件被选中");}}}/***把文本区上的内容保存到指定文件上*@param f-保存到的文件对象*/public void saveFile(File f){try{FileWriter file = new FileWriter(f);BufferedWriter out = new BufferedWriter(file);out.write(textArea.getText(), 0,textArea.getText().length());out.close();}catch( Exception e ){label.setText("写文件发生错误");}}public static void main(String[] args){new SaveFile();}}3.在一个文件中,每行存的是整数,各行整数个数不等,要求读这个文件,然后计算每行整数的和,并存到另一个文件中。
程序运行结果:计算文件中的整数和源文件:FileIntegerSum.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;import java.util.*;/***9.3在一个文件中,每行存的是整数,各行整数个数不等,<BR>*要求读如这个文件,然后计算每行整数的和,并存到另一个文件中。
<BR>*@author黎明你好**/public class FileIntegerSum extends JFrame implements ActionListener {private static final long serialVersionUID = 1L;private JButton buttonSave, buttonCount, buttonOpen;// 按钮:保存,计算,保存private JTextArea textArea;//文本区private JLabel label;//显示当前文件的绝对路径的labelprivate JFileChooser filedialog;//文件选择对话框private JPanel panel;//布局用的panelprivate File file = null;//文件对象public FileIntegerSum(){super("第九章,第三题 - 整数求和");buttonOpen = new JButton("打开文件");buttonSave = new JButton("保存到...");buttonCount = new JButton("计算结果");label = new JLabel(" ");panel = new JPanel();textArea = new JTextArea();filedialog = new JFileChooser();filedialog.addChoosableFileFilter(new MyFileFilter("txt"));buttonOpen.addActionListener(this);buttonSave.addActionListener(this);buttonCount.addActionListener(this);// 给按钮加监控panel.add(buttonOpen);panel.add(buttonCount);panel.add(buttonSave);// 把按钮添加到panel面板上this.add(panel, BorderLayout.NORTH);this.add(new JScrollPane(textArea), BorderLayout.CENTER);this.add(label, BorderLayout.SOUTH);this.setBounds(50, 50, 500, 300);this.validate();this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public void actionPerformed(ActionEvent e){if (e.getSource() == buttonOpen){filedialog.setDialogTitle("打开");int result = filedialog.showOpenDialog(this);if (result == JFileChooser.APPROVE_OPTION){file = filedialog.getSelectedFile();label.setText("" + file.getAbsolutePath());readFiletoText(file);}else if (result == JFileChooser.CANCEL_OPTION)label.setText("你没有选择任何文件\n");}if (e.getSource() == buttonSave){filedialog.setDialogTitle("另存为");int result = filedialog.showSaveDialog(this);if (result == JFileChooser.APPROVE_OPTION){file = filedialog.getSelectedFile();label.setText("" + file.getAbsolutePath());saveAsText(file);}else if (result == JFileChooser.CANCEL_OPTION){label.setText("你没有选择任何文件\n");}}if (e.getSource() == buttonCount){textArea.setText(null);if (this.file != null)countResult(file);}}/***将指定的文件显示在文本区上*@param file-指定的文件*/public void readFiletoText(File file){try{FileReader file_reader = new FileReader(file);BufferedReader in = new BufferedReader(file_reader);String ss = new String();while ((ss = in.readLine()) != null){textArea.append(ss + '\n');}in.close();}catch( FileNotFoundException e2 ){label.setText("文件没有找到\n");}catch( IOException e3 ){e3.printStackTrace();}textArea.setCaretPosition(0);}/***将文本区内容保存到指定文件*@param file-指定的文件*/public void saveAsText(File file){try{FileWriter file_writer = new FileWriter(file);BufferedWriter out = new BufferedWriter(file_writer);out.write(textArea.getText(), 0,(textArea.getText().length()));out.flush();out.close();}catch( FileNotFoundException e2 ){label.setText("文件没有找到\n");}catch( IOException e3 ){}}/***计算指定文件上,每行整数之和,并显示在文本区上*@param file-指定的文件*/public void countResult(File file){try{FileReader file_reader = new FileReader(file);BufferedReader in = new BufferedReader(file_reader);String temp = new String();while ((temp = in.readLine()) != null){int number = 0;StringTokenizer token = new StringTokenizer(temp, " ,.");while (token.hasMoreTokens()){number += Integer.parseInt(token.nextToken());}textArea.append(temp + "---------相加结果是:" + number +}in.close();}catch( Exception e2 ){label.setText("error" + e2 + '\n');}}public static void main(String args[]){new FileIntegerSum();}}4.在一个文本区中输入数据,把输入的数据分析成各个单词,然后排序显示到第二个文本区中,并通过文件保存对话框保存到文件中。