Java语言程序设计(郑莉)第九章课后习题答案
- 格式:doc
- 大小:576.50 KB
- 文档页数:36
Java语言程序设计(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protecte及无修饰符. public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限). Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。
《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;}}。
《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 )把整个参数引起来。
习题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语⾔概述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数组引⽤相同。
第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个字节或字符。
Java语言程序设计课后习题答案全集Java语言程序设计是一门广泛应用于软件开发领域的编程语言,随着其应用范围的不断扩大,对于掌握Java编程技巧的需求也逐渐增加。
为了帮助读者更好地掌握Java编程,本文将提供Java语言程序设计课后习题的全集答案,供读者参考。
一、基础知识题1. 代码中的注释是什么作用?如何使用注释.答:注释在代码中是用来解释或者说明代码的功能或用途的语句,编译器在编译代码时会自动忽略注释。
在Java中,有三种注释的方式:- 单行注释:使用"// " 可以在代码的一行中加入注释。
- 多行注释:使用"/* */" 可以在多行中添加注释。
- 文档注释:使用"/** */" 可以添加方法或类的文档注释。
2. 什么是Java的数据类型?请列举常见的数据类型。
答:Java的数据类型用来指定变量的类型,常见的数据类型有:- 基本数据类型:包括整型(byte、short、int、long)、浮点型(float、double)、字符型(char)、布尔型(boolean)。
- 引用数据类型:包括类(class)、接口(interface)、数组(array)等。
二、代码编写题1. 编写Java程序,输入两个整数,求和并输出结果。
答:```javaimport java.util.Scanner;public class SumCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个整数:");int num1 = scanner.nextInt();System.out.print("请输入第二个整数:");int num2 = scanner.nextInt();int sum = num1 + num2;System.out.println("两个整数的和为:" + sum);}}```三、综合应用题1. 编写Java程序,实现学生信息管理系统,要求包括以下功能:- 添加学生信息(姓名、年龄、性别、学号等);- 修改学生信息;- 删除学生信息;- 查询学生信息。
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()。
第9章网络通信【1】java提供了哪几种网络通信模式?[解答]:基于TCP/IP协议的面向连接的通信模式,基于UDP协议的面向无连接的通信模式。
【2】java的套接字网络通信方式分为哪几种?[解答]:基于TCP/IP协议:客户端套接字,服务器端套接字。
基于UDP协议:用户数据报套接字,广播数据报套接字。
【3】什么是socket,怎样建立socket连接?建立连接时,客户端和服务器端有什么不同?[解答]:Socket就是套接字,是IP地址和端口号的组合。
当两个网络程序需要通信时,它们可以通过使用Socket类建立套接字连接。
服务器端建立Socket以后,要执行一个等待的方法,以方便客户端来连接。
客户端建立Socket以后即与服务器端进行连接,成功握手以后,双方产生同样的Socket对象。
【4】请列举常用的协议及其端口号。
[解答]:ftp 21/tcptelnet 23/tcpsmtp 25/tcphttp 80/tcppop3 110/tcpsnmp 161/udphttps 443/tcphttps 443/udppop3 110/tcp【5】试描述用Socket建立连接的基本程序框架。
[解答]:(1)客户端建立套接字对象,指定服务器IP和端口号。
(2)服务器端建立套接字,并指定端口号。
(3)服务器端监听本机的端口的状态:执行accept()方法。
(4)客户端程序在对象产生以后以及,服务器端的程序监听到有连接以后都会产生一个Socket类的实例。
(5)对这两个实例中对应的输入流和输出流进行操作,即完成通信过程。
【6】说明客户端如何与服务器端进行连接。
[解答]:TCP/IP的方式是:客户端产生Socket对象的同时产生与对应端口号的服务器连接的动作。
UDP数据报的方式是:客户端建立DatagramSocket对象,建立报文DatagramPacket对象,并指定发送的IP地址,调用socket对象的send方法进行连接并发送数据。
第九章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.在一个文件中,每行存的是整数,各行整数个数不等,要求读这个文件,然后计算每行整数的和,并存到另一个文件中。
第9章继承与派生课后习题参考答案一、单项选择题1.下列有关派生类的叙述中,错误的是(D)。
A.一个派生类至少有一个基类B.派生类的默认继承方式是privateC.一个派生类可以作为另一个派生类的基类D.派生类只继承了基类的公有成员和保护成员2.下列有关类继承的叙述中,错误的是(B)。
A.继承可以实现软件复用B.派生类没有继承基类的私有成员C.虚基类可以解决由多继承产生的二义性问题D.派生类构造函数要负责调用基类的构造函数3.有如下类定义:class XX{int xdata;public:XX(int n=0):xdata(n){}};class YY:public XX{int ydata;public:YY( int m=0,int n=0):XX(m),ydata(n){}};YY类的对象包含的数据成员的个数为(B)。
A.1B.2C.3D.44.设类的定义如下,且int型数据在内存中用4个字节存储,则类B 的对象占据内存空间的字节数为(C)。
class A{int b;protected:int a;};class B:public A{{int c;public:int getC(){return c;}};A.4B.8C.12D.165.如果派生类以protected方式继承基类,则原基类的protected成员和public成员在派生类中的访问权限分别是(D)。
A.private和publicB.private和protectedC.protected和publicD.protected和protected6.可以用p.a的形式访问派生类对象p的基类成员a,则a是(D)。
A.私有继承的公有成员B.公有继承的私有成员C.公有继承的保护成员D.公有继承的公有成员7.设有如下类定义:class Base {protected:void fun(){}//…};class Derived:Base{//…};则Base类中的成员函数fun(),在Derived类中的访问权限是(C)。
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.。
第9章 抽象类与接口复习题9.1 答:(c)和(f)定义了合法抽象类。
9.2 答:约束其子类必须实现这2个方法。
9.3 答:(d)是正确的。
9.4 答:不正确,原因是类型转换错误。
9.5 答:使用接口提供了一般程序设计(generic programming)的形式。
允许参数接收范围更广的类型。
同时由于Java 不支持类的多继承,使用接口可以使类继承一个父类的同时实现多个接口。
9.6 答:(1)如果没有覆盖clone 方法,则编译出错,找不到clone 方法。
(2)如果没有实现Cloneable 接口,则House 类的对象不能clone,执行如下语句时,h2得到的是null。
House h1 = new House(); House h2 = (House)(h1.clone());9.7 答:输出结果: false true9.8 答:错误为:GeometricObject y = x.clone();clone()方法的返回值是Object 类,赋值给y 时需要强制类型转换。
9.9 答:Object[] objs = new int[10]; 不可以 Object[] objs = new String[100]; 可以 Object[] objs = new Object[50]; 可以 Object[] objs = new Calendar[10]; 可以9.10答:略9.11答:Integer i = new Integer("23"); //正确Integer i = new Integer(23); //正确 Integer i = Integer.valueOf("23");//正确 Integer i = Integer.parseInt("23", 8);//正确 Double d = new Double();//错误课后答案网ww w.kh da w .c omDouble d = Double.valueOf("23.45"); //正确int i = (Integer.valueOf("23")).intValue(); //正确double d = (Double.valueOf("23.4")).doubleValue(); //正确 int i = (Double.valueOf("23.4")).intValue(); //正确 String s = (Double.valueOf("23.4")).toString(); //正确9.12 答:可以使用parseXXX 方法和toString 方法9.13 答:向下类型转换时,没有保证类型的一致。
Java语言程序设计(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有 public,private,protecte及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为private的成员只能被这个类本身访问,在类外不可见。
Java语言程序设计第2版(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加stati c修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加sta t ic修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有publ ic(公共类)及无修饰符(默认类)两种。
区别:当使用publ ic修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种?他们对类成员分别有哪些访问限制的作用?答:类成员的访问控制符有public,private,protect e及无修饰符.public(公有的):用public修饰的成分表示公有的,也就是它可以被其他任何对象访问(前提是对累成员所在的类访问有访问权限).Private(保护的):类中限定为pr ivate的成员只能被这个类本身访问,在类外不可见。
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之间的整数,根据输入偏大、偏小、正确,程序将显示不同的图标。