《Java语言程序设计(基础篇)》(第10版 梁勇 著)第九章练习题答案
java语言程序设计基础篇第十版课后答案
第一章1.1public class Test{public static void main(String[]args){System.out.println("Welcome to Java!"); System.out.println("Welcome to Computer Science!");System.out.println("Progr amming is fun.");}}1.2public class Test{public static void main(String[]args){for(int i=0;i<=4;i++){System.out.println("Welcome to Java!");}}}1.3public class Test{public static void main(String[]args){System.out.println("]");System.out.printl n("]");System.out.println("]]");System.out.println("]]");}}public class Test{public static void main(String[]args){System.out.println("A"); System.out.println("A A");System.out.println("AAAAA");System.out.println("A A");}}public class Test{public static void main(String[]args){System.out.println("V V");System.out.println("V V");System.out.println("V V");System.out.println(" V");}}1.4public class Test{public static void main(String[]args){System.out.println("a a^2a^3");System.out.println("111");System.out.println("248");System.out.println("3 927");System.out.println("41664");}}1.5public class Test{public static void main(String[]args){System.out.println((9.5*4.5-2.5*3)/(45.5-3.5) );}}1.6public class Test{public static void main(String[]args){int i=1,sum=0;for(;i<=9;i++)sum+ =i;System.out.println(sum);}1.7public class Test{public static void main(String[]args){System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11));System.out.println(4*(1.0-1.0/3+1.0/5-1.0/7+1.0/9-1.0/11+1.0/13));}}1.8public class Test{public static void main(String[]args){final double PI=3.14; double radius=5.5;System.out.println(2*radius*PI);System.out.println(PI*radius*radius);}}1.9public class Test{public static void main(String[]args){System.out.println(7.9*4.5);System.out.p rintln(2*(7.9+4.5));}}1.10public class Test{public static void main(String[]args){double S=14/1.6;double T=45*60+30;double speed=S/T;System.out.println(speed);}1.11public class Test{public static void main(String[]args){int BN=312032486; //original person numbers double EveryYS,EveryYBP,EveryYDP,EveryYMP;EveryY S=365*24*60*60;EveryYBP=EveryYS/7;EveryYDP=EveryYS/13;Every YMP=EveryYS/45;int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP;FirstYP=(int)(BN+EveryYBP+EveryYMP-EveryYDP);SecondYP=(int)(FirstYP +EveryYBP+EveryYMP-EveryYDP);ThirdYP=(int)(SecondYP+EveryYBP+Ev eryYMP-EveryYDP);FourthYP=(int)(ThirdYP+EveryYBP+EveryYMP-EveryYD P);FivthYP=(int)(FourthYP+EveryYBP+EveryYMP-EveryYDP);System.out.pri ntln(FirstYP);System.out.println(SecondYP);System.out.println(ThirdYP);Syste m.out.println(FourthYP);System.out.println(FivthYP);}}1.12public class Test{public static void main(String[]args){double S=24*1.6; double T=(1*60+40)*60+35;double speed=S/T;System.out.println(sp eed);}}1.13import java.util.Scanner;public class Test{public static void main(String[]args){Scanner input=new Scan ner(System.in);System.out.println("input a,b,c,d,e,f value please:");double a=input.nextDouble();double b=input.nextDouble();double c=input.nextDouble();double d=input. nextDouble();double e=input.nextDouble();第二章package cn.Testcx;import java.util.Scanner;public class lesson2{public static void main(String[]args){@SuppressWarnings("resource")Scanner in put=new Scanner(System.in);System.out.print("请输入一个摄氏温度:");double Celsius=input.nextDouble();double Fahrenheit=(9.0/5)*Celsius+3 2;System.out.println("摄氏温度:"+Celsius+"度"+"转换成华氏温度为:"+Fahrenheit+"度");System.out.print("请输入圆柱的半径和高:");double radius=input.nextDouble();int higth=input.nextInt();double are as=radius*radius*Math.PI;double volume=areas*higth;System.out.println("圆柱体的面积为:"+areas);System.out.println("圆柱体的体积为:"+volume);System.out.print("输入英尺数:");double feet=input.nextDouble();double meters=feet*0.305;System.out.print ln(feet+"英尺转换成米:"+meters);System.out.print("输入一个磅数:");double pounds=input.nextDouble();double kilograms=pounds*0.454;Syste m.out.println(pounds+"磅转换成千克为:"+kilograms);System.out.println("输入分钟数:");long minutes=input.nextInt();long years=minutes/(24*60*365);long days=(minutes%(24*60*365))/(24*60);System.out.println(minutes+"分钟"+"有"+years+"年和"+days+"天");long totalCurrentTimeMillis=System.currentTimeMillis();long totalSeconds=t otalCurrentTimeMillis/1000;long currentSeconds=totalSeconds%60;long totalM inutes=totalSeconds/60;long currentMinutes=(totalSeconds%(60*60))/60;long currenthours=(totalMinutes/60)%24;System.out.print("输入时区偏移量:");byte zoneOffset=input.nextByte();long currentHour=(currenthours+(zoneOf fset*1))%24;System.out.println("当期时区的时间为:"+currentHour+"时"+currentMinutes+"分"+currentSeconds+"秒");System.out.print("请输入v0,v1,t:");double v0=input.nextDouble();double v1=input.nextDouble();doublet=input.nextDouble();float a=(float)((v1-v0)/t);System.out.println("平均加速度a="+a);System.out.println("输入水的重量、初始温度、最终温度:");double water=input.nextDouble();double initialTemperature=input.nextDou ble();double finalTemperature=input.nextDouble();double Q=water*(finalTemp erature-initialTemperature)*4184;System.out.println("所需热量为:"+Q);System.out.print("输入年数:");int numbers=input.nextInt();long oneYearsSecond=365*24*60*60;Longpop ulation=(long)((312032486+((oneYearsSecond/7.0)+(oneYearsSecond/45.0)-(oneYearsSecond/13.0))*numbers));System.out.println("第"+numbers+"年后人口总数为:"+population);System.out.print("输入速度单位m/s和加速度a单位m/s2:");double v=input.nextDouble();double a1=input.nextDouble();double l engthOfAirplane=(Math.pow(v,2))/(2*a1);System.out.println("最短长度为:"+lengthOfAirplane);System.out.print("输入存入的钱:");double money=input.nextInt();double monthRate=5.0/1200;for(int i=1;i<7; i++){double total=money*(Math.pow(1+monthRate,i));System.out.println("第"+i+"个月的钱为:"+total);//告诉我书上的银行在哪里,我要去存钱,半年本金直接翻6倍、、、}System.out.print("用户请输入身高(英寸)、体重(磅):");double height=input.nextDouble();double weight=input.nextDouble(); double BMI=(weight*0.45359237)/(Math.pow((height*0.0254),2));System.out.println("BMI的值为"+BMI);System.out.print("输入x1和y1:");System.out.print("输入x2和y2:");double x1=input.nextDouble();double y1=input.nextDouble();double x2 =input.nextDouble();double y2=input.nextDouble();double point1=Math.pow((x2-x1),2);double point2=Math.pow((y2-y1),2);double distance=Math.pow((point1+point2),(1.0/2));//也可以Math.pow((point1+point2),0.5)System.out.println("两点间的距离为:"+distance);System.out.print("输入六边形的边长:");double side=input.nextDouble();double area=(3*(Math.pow(3,0.5))*(Math.p ow(side,2)))/2;System.out.println("六边形的面积为:"+area);}}。
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")。
Java语言程序设计基础篇(第10版) 梁勇 课后习题答案
System.out.println("Programming is fun .");
}
}
1.2 public class Test{
public static void main(String[] args){
for(int i = 0;i <= 4;i++){
System.out.println("Welcome to Java !");
public static void main(String[] args){ double S = 14 / 1.6;
double T = 45 * 60 + 30; double speed = S / T; System.out.println(speed); } } 1.11 public class Test{ public static void main(String[] args){ int BN = 312032486; //original person numbers double EveryYS,EveryYBP,EveryYDP,EveryYMP; EveryYS = 365 * 24 * 60 * 60; EveryYBP = EveryYS / 7; EveryYDP = EveryYS / 13; EveryYMP = EveryYS / 45; int FirstYP,SecondYP,ThirdYP,FourthYP,FivthYP; FirstYP = (int)(BN + EveryYBP + EveryYMP - EveryYDP); SecondYP = (int)(FirstYP + EveryYBP + EveryYMP - EveryYDP); ThirdYP = (int)(SecondYP + EveryYBP + EveryYMP - EveryYDP); FourthYP = (int)(ThirdYP + EveryYBP + EveryYMP - EveryYDP); FivthYP = (int)(FourthYP + EveryYBP + EveryYMP - EveryYDP); System.out.println(FirstYP); System.out.println(SecondYP); System.out.println(ThirdYP); System.out.println(FourthYP); System.out.println(FivthYP); } } 1.12 public class Test{ public static void main(String[] args){ double S = 24 * 1.6; double T = (1 * 60 + 40) * 60 + 35; double speed = S / T; System.out.println(speed); } } 1.13 import java.util.Scanner; public class Test{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("input a,b,c,d,e,f value please:"); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double d = input.nextDouble(); double e = input.nextDouble();
《Java基础入门》_课后习题答案大一计算机专业9
《Java基础入门》课后习题答案第9章JDBC一、填空题1、Java Database Connectivity2、java.sql.*3、classpath4、registerDriver()5、next()二、判断题1、对2、错3、对4、错5、错三、选择题1、A2、C3、A4、D5、AC四、简答题1、JDBC是一套用于执行SQL语句的Java API。
应用程序可通过这套API连接到关系型数据库,并使用SQL语句来完成对数据库中数据的查询、新增、更新和删除等操作。
2、(1)加载数据库驱动(2)通过DriverManager获取数据库连接(3)通过Connection对象获取Statement对象(4)使用Statement执行SQL语句(5)操作ResultSet结果集(6)关闭连接,释放资源3、(1)代码的可读性和可维护性(2)PreparedStatement尽最大可能提高性能,因为预编译语句有可能被重复调用,所以语句在被DB 的编译器编译后的执行代码被缓存下来,那么下次调用时只要是相同的预编译语句就不需要编译,只要将参数直接传入编译过的语句执行代码中(相当于一个函数)就会得到执行。
(3)极大地提高了安全性传。
递给PreparedStatement对象的参数可以被强制进行类型转换,使开发人员可以确保在插入或查询数据时与底层的数据库格式匹配;在公共Web站点环境下,防止Sq注入问题。
五、编程题1、参考答案public static void main(String[] args) throws Exception {// int i = insert();// int i = delete();// int i = update();select();// System.out.println(i);}// 获取连接对象private static Connection getConn() {String driver = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/javatest";String username = "root";String password = "1234";Connection conn = null;try {Class.forName(driver); // classLoader,加载对应驱动conn = DriverManager.getConnection(url, username, password);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return conn;}// 插入操作private static int insert() {Connection conn = getConn();int i = 0;String sql = "insert into tb_user(name,sex,email,birthday) values(?,?,?,?)";PreparedStatement pstmt;try {pstmt = conn.prepareStatement(sql);pstmt.setString(1, "itcast");pstmt.setString(2, "男");pstmt.setString(3, "itcast@");pstmt.setString(4, "2000-01-01");i = pstmt.executeUpdate();pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}return i;}// 删除操作private static int delete() {Connection conn = getConn();int i = 0;String sql = "delete from tb_user where name=?";PreparedStatement pstmt;try {pstmt = conn.prepareStatement(sql);pstmt.setString(1, "itcast");i = pstmt.executeUpdate();} catch (Exception e) {e.printStackTrace();}return i;}// 更新操作private static int update() {Connection conn = getConn();int i = 0;String sql = "update tb_user set name=? where name =?";PreparedStatement pstmt;try {pstmt = conn.prepareStatement(sql);pstmt.setString(1, "itcast");pstmt.setString(2, "abc");i = pstmt.executeUpdate();System.out.println("resutl: " + i);pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}return i;}// 查询操作private static void select() {Connection conn = getConn();String sql = "select * from tb_user";PreparedStatement pstmt;try {pstmt = conn.prepareStatement(sql);ResultSet rs = pstmt.executeQuery();while (rs.next()) {int id = rs.getInt("id"); // 通过列名获取指定字段的值String name = rs.getString("name");String sex = rs.getString("sex");String email = rs.getString("email");Date birthday = rs.getDate("birthday");System.out.println(id + " | " + name + " | " + sex + " | " + email + " | " + birthday);}pstmt.close();conn.close();} catch (Exception e) {e.printStackTrace();}}2、参考答案import java.sql.*;public class Test {public static void main(String[] args) throws Exception {transferAccounts(2, 1, 100);}public static void transferAccounts(int fromid,int toid,int transferMoney) throwsException{ Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql://localhost:3306/jdbc";Connection con = DriverManager.getConnection(url,"root", "root");int fromMoney = getMoney(fromid);// 转出账户String sql = "update tb_count set money=? where id =?";PreparedStatement ps = con.prepareStatement(sql);ps.setInt(1, fromMoney-transferMoney);ps.setInt(2, fromid);// 转入账户int toMoney = getMoney(toid);String sql2 = "update tb_count set money=? where id =?";PreparedStatement ps2 = con.prepareStatement(sql2);ps2.setInt(1, toMoney+transferMoney);ps2.setInt(2, toid);ps.executeUpdate();ps2.executeUpdate();ps.close();ps2.close();con.close();}// 获取当前账户id的账户余额public static int getMoney(int id) throws Exception{Class.forName("com.mysql.jdbc.Driver");String url = "jdbc:mysql://localhost:3306/jdbc";Connection con = DriverManager.getConnection(url,"root", "root");String sql = "select money from tb_count where id =?";PreparedStatement ps = con.prepareStatement(sql);ps.setInt(1, id);ResultSet resultSet = ps.executeQuery();int money = 0;while(resultSet.next()){money = resultSet.getInt(1);}ps.close();con.close();return money;}}。
Java语言程序设计(基础篇)第10版习题答案Chapter9-1
Java语⾔程序设计(基础篇)第10版习题答案Chapter9-1(矩形类 Rectangle)遵照9.2节中 Circle 类的例⼦,设计⼀个名为 Rectangle 的类表⽰矩形。
这个类包括:两个名为 width 和 height 的 double 型数据域,它们分别表⽰矩形的宽和⾼。
width 和 height 的默认值都为1。
创建默认矩形的⽆参构造⽅法⼀个创建 width 和 height 为指定值的矩形的构造⽅法。
⼀个名为 getArea() 的⽅法返回这个矩形的⾯积。
⼀个名为 getPerimeter() 的⽅法返回周长。
画出该矩形的 UML 图并实现这个类。
编写⼀个测试程序,创建两个 Rectangle 对象——⼀个矩形的宽为 4 ⽽⾼为 40,另⼀个矩形的宽为3.5 ⽽⾼为 35.9 。
按照这个顺序显⽰每个矩形的宽、⾼、⾯积、周长。
程序代码:public class Rectangle {private double width;private double height;public Rectangle(){width=1.0;height=1.0;}public Rectangle(double width,double height) {this.width=width;this.height=height;}public double getWidth() {return width;}public double getHeight() {return height;}public double getArea() {return width*height;}public double getPerimeter() {return 2*(width+height);}public static void main(String[] args) {// TODO Auto-generated method stubRectangle t1=new Rectangle(4,40);Rectangle t2=new Rectangle(3.5,35.9);System.out.println("width:"+t1.getWidth()+" height:"+t1.getHeight()+" Area:"+t1.getArea()+" Per:"+t1.getPerimeter());System.out.println("width:"+t2.getWidth()+" height:"+t2.getHeight()+" Area:"+t2.getArea()+" Per:"+t2.getPerimeter());}}运⾏结果:width:4.0 height:40.0 Area:160.0 Per:88.0width:3.5 height:35.9 Area:125.64999999999999 Per:78.8。
java语言程序设计基础篇第十版练习答案精编
j a v a语言程序设计基础篇第十版练习答案精编Document number:WTT-LKK-GBB-08921-EIGG-2298601import class Exercise14_01 extendsApplication {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}02import class Exercise14_02 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}03import class Exercise14_03 extends Application {@Override One is to use the hint in the book.ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 52; i++) {(i);}HBox pane = new HBox(5);;().add(new ImageView("image/card/" + (0) +".png"));().add(new ImageView("image/card/" + (1) +".png"));().add(new ImageView("image/card/" + (2) +".png"));Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}04import class Exercise14_04 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}05import class Exercise14_05 extends Application {@Override dd(txt);}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}06import class Exercise14_06 extends Application {@Override dd(rectangle);}}Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}07import class Exercise14_07 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}08import class Exercise14_08 extends Application {@Override ng"), j, i);}}Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}09import class Exercise14_09 extends Application {@Override Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class FanPane extends Pane {double radius = 50;public FanPane() {Circle circle = new Circle(60, 60, radius);;;getChildren().add(circle);Arc arc1 = new Arc(60, 60, 40, 40, 30, 35);; ddAll(arc1, arc2, arc3, arc4);}}10import class Exercise14_10 extends Application {@Override ddAll, ;Arc arc2 = new Arc(100, 140, 50, 20, 180, 180); ;;().addAll(ellipse, arc1, arc2,new Line(50, 40, 50, 140), new Line(150, 40, 150, 140));Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}11import class Exercise14_11 extends Application {@Override ddAll(circle, ellipse1, ellipse2,circle1, circle2, line1, line2, line3, arc);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}12import class Exercise14_12 extends Application {@Override ddAll(r1, text1, r2, text2, r3, text3, r4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}13import class Exercise14_13 extends Application {@Override ddAll(arc1, text1, arc2, text2, arc3, text3, arc4, text4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}14import class Exercise14_14 extends Application {@Override ddAll(r1, r2, line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}15import class Exercise14_15 extends Application {@Override ddAll(polygon, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}16import class Exercise14_16 extends Application {@Override ind().divide(3));().bind());().bind().divide(3));;Line line2 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind());().bind().multiply(2).divide(3));;Line line3 = new Line(0, 0, 0, 0);().bind().divide(3));().bind().divide(3));().bind());;Line line4 = new Line(0, 0, 0, 0);().bind().multiply(2).divide(3));().bind().multiply(2).divide(3));().bind());;().addAll(line1, line2, line3, line4);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}17import class Exercise14_17 extends Application {@Override ddAll(arc, line1, line2, line3, circle, line4, line5, line6, line7, line8);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}18import class Exercise14_18 extends Application {@Override ddAll(polyline, line1, line2,line3, line4, line5, line6, text1, text2);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}19import class Exercise14_19 extends Application {@Override ddAll(polyline1, polyline2, line1,line2,line3, line4, line5, line6, text1, text2,text3,text4, text5, text6, text7);Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}20import class Exercise14_20 extends Application {@Override dd(new Line(x1, y1, x2, y2));dd(new Line(x2, y2, (x2 + (arctan + set45) * arrlen)),((y2)) + (arctan + set45) * arrlen)));().add(new Line(x2, y2, (x2 + (arctan - set45) * arrlen)),((y2)) + (arctan - set45) * arrlen)));}/*** The main method is only needed for the IDE with limited* JavaFX support. Not needed for running from the command line.*/public static void main(String[] args) {launch(args);}}21import class Exercise14_21 extends Application {@Override istance(x2, y2) + "");().addAll(circle1, circle2, line, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}22import class Exercise14_22 extends Application {@Override ddAll(circle1, circle2, line, text1, text2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}23import class Exercise14_23 extends Application {@Override ddAll(r1, r2, text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}24import class Exercise14_24 extends Application {@Override ddAll(polygon, new Circle(x5, y5, 10), text);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}25import class Exercise14_25 extends Application {@Override ddAll(circle, polygon);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}}26import class Exercise14_26 extends Application {@Override ddAll(clock1, clock2);Not needed for running from the command line. */public static void main(String[] args) {launch(args);}27import class Exercise14_27 extends Application {@OverrideNot needed for running from the command line. */public static void main(String[] args) {launch(args);}}class DetailedClockPane extends Pane {private int hour;private int minute;private int second;lear();getChildren().addAll(circle, sLine, mLine, hLine);dd(new Line(xOuter, yOuter, xInner, yInner));}dd(text);}}}28import class Exercise14_28 extends Application {@OverrideNot needed for running from the command line.*/public static void main(String[] args) {launch(args);}}class ClockPaneWithBooleanProperties extends Pane { private int hour;private int minute;private int second;private boolean hourHandVisible = true;private boolean minuteHandVisible = true; private boolean secondHandVisible = true;public boolean isHourHandVisible() {return hourHandVisible;}public void setHourHandVisible(boolean hourHandVisible) {= hourHandVisible;paintClock();}public boolean isMinuteHandVisible() {return minuteHandVisible;}public void setMinuteHandVisible(boolean minuteHandVisible) {= minuteHandVisible;paintClock();}public boolean isSecondHandVisible() {return secondHandVisible;public void setSecondHandVisible(boolean secondHandVisible) {= secondHandVisible;paintClock();}lear();getChildren().addAll(circle, t1, t2, t3, t4);if (secondHandVisible) {getChildren().add(sLine);}if (minuteHandVisible) {getChildren().add(mLine);}if (hourHandVisible) {getChildren().add(hLine);}}}import class Exercise14_29 extends Application {final static double HGAP = 20;final static double VGAP = 20;final static double RADIUS = 5;final static double LENGTH_OF_SLOTS = 40;final static double LENGTH_OF_OPENNING = 15;final static double Y_FOR_FIRST_NAIL = 50;final static double NUMBER_OF_SLOTS = 9;final static double NUMBER_OF_ROWS =NUMBER_OF_SLOTS - 2;@Override dd(c);}}dd(new Line(x, y, x, y + LENGTH_OF_SLOTS)); }dd(new Line(centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP,y + LENGTH_OF_SLOTS, centerX -(NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP,y + LENGTH_OF_SLOTS));dd(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 + NUMBER_OF_ROWS * HGAP, y));().add(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - (NUMBER_OF_ROWS - 1) * HGAP / 2 - HGAP, y));dd(new Line(centerX - HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX - HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));().add(new Line(centerX + HGAP / 2,Y_FOR_FIRST_NAIL + RADIUS,centerX + HGAP / 2, Y_FOR_FIRST_NAIL - LENGTH_OF_OPENNING));Not needed for running from the command line.*/public static void main(String[] args) { launch(args);}}。
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章 习题参考答案
第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编程,本文将提供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语言程序设计(一)课后习题第九章(附答案)九、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()。
JAVA语言程序设计(基础篇)答案
3.4import javax.swing.*;public class AdditionTutor{public static void main(String[] args){int number1=(int)(System.currentTimeMillis()%100);int number2=(int)(System.currentTimeMillis()*5%100);String answerString=JOptionPane.showInputDialog("what is "+ number1 +"+ "+ number2+" ?");int answer=Integer.parseInt(answerString);JOptionPane.showMessageDialog(null,number1 +" + "+ number2 +" = "+answer+" is "+(number1+number2==answer));}}3.10import javax.swing.JOptionPane;public class ComputeTaxWithSelectionStatement{public static void main(String[] args){//Prompt the user to enter filing statusString statusString = JOptionPane.showInputDialog("Enter the filing status:\n"+"(0-single filer,1-married jointly,\n"+"2-married separately,3-head of household)");int status = Integer.parseInt(statusString);//Prompt the user to enter taxable incomeString incomeString = JOptionPane.showInputDialog("Enter the taxable income:");double income = Double.parseDouble(incomeString);//Comput taxdouble tax=0;if (status == 0){//Compute tax for single filersif (income <= 6000)tax = income * 0.10;else if (income <= 27950)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 67700)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(income - 27950) * 0.27;else if (income <= 141250)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (income - 67700) * 0.30;else if (income <=307050)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 +(income - 141250) * 0.35;elsetax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 -67700) * 0.30 +(307050 - 141250) * 0.35 + (income - 307050) * 0.386;}else if (status == 1){//Compute tax for married file jointly if (income <= 12000)tax = income * 0.10;else if (income <= 46700)tax = 12000 * 0.10 + (income - 12000) * 0.15;else if (income <= 112850)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(income - 46700) * 0.27;else if (income <= 171950)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (income - 112850) * 0.30;else if (income <= 307050)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (141250 - 112850) * 0.30 +(income - 307050) * 0.35;elsetax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700 ) * 0.27 + (171950 - 112850) * 0.30 +(307050 - 171950) * 0.35 + (income - 307050) * 0.386;}else if (status == 2){//Compute tax for married separately if (income <= 6000)tax = income * 0.10;else if (income <= 23350)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 56425)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(income - 23350) * 0.27;else if (income <= 85975)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (income - 56425) * 0.30;else if (income <= 153525)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(income - 85975) * 0.35;elsetax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(153525 - 85975) * 0.35 + (income - 153525) * 0.386;}else if (status == 3){//Compute tax for head of householdif (income <= 10000)tax = income * 0.10;else if (income <= 37450)tax = 10000 * 0.10 + (income - 10000) * 0.15;else if (income <= 96700)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(income - 37450) * 0.27;else if (income <= 156600)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (income - 96700) * 0.30;else if (income <= 307050)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(income - 156600) * 0.35;elsetax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(307050 - 156600) * 0.35 + (income - 307050) * 0.386;}else{System.out.println("Error: invalid status");System.exit(0);}//Display the resultJOptionPane.showMessageDialog(null,"Tax is " +(int)(tax * 100) / 100.0);}}4.11public class ZhengChu{public static void main(String[] args){int count=0;for(int i=100;i<=200;i++){if((i%5==0||i%6==0)&&i%30!=0){System.out.print(" "+ i);count++;if(count%10==0)System.out.println();}}}}4.14public class ASCII{public static void main(String[] args){int count = 0;for(int i = 33; i <= 126; i++){count++;char ch = (char)i;System.out.print(" " + ch);if(count % 10 == 0)System.out.println();}}}4.17import javax.swing.JOptionPane;public class FindSalesAmount{/**Main method*/public static void main(String[] args){//The commission soughtString COMMISSION_SOUGHTString = JOptionPane.showInputDialog("Enter the COMMISSION_SOUGHT :");double COMMISSION_SOUGHT = Double.parseDouble(COMMISSION_SOUGHTString);double commission = 0;double salesAmount;for (salesAmount = 0.01;commission <= COMMISSION_SOUGHT;){salesAmount += 0.01; //防止犯off-by-one错误,先判断在做自加!if (salesAmount >= 10000.01)commission =5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;else if (salesAmount >= 5000.01)commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;elsecommission = salesAmount * 0.08;}String output ="The sales amount $" + (int)(salesAmount * 100) / 100.0 +"\n is needed to make a commission of $" + COMMISSION_SOUGHT;JOptionPane.showMessageDialog(null,output);}}5.6import javax.swing.JOptionPane;public class PrintPyramid{public static void main(String[] args){String input = JOptionPane.showInputDialog("Enter the number of lines:");int numberOfLines = Integer.parseInt(input);displayPattern(numberOfLines);}public static void displayPattern(int n){for (int row = 1;row <= n;row++){for (int column = 1;column <= n - row;column++)System.out.print(" ");for (int num = row;num >= 1;num--)System.out.print((num >= 10) ? " " + num : " " + num);System.out.println();}}}5.18public class MathSuanFa{public static void main(String[] args){double A = Math.sqrt(4);double B = (int)Math.sin(2 * Math.PI);double C = (int)Math.cos(2 * Math.PI);double D = (int)Math.pow(2, 2);double E = (int)Math.log(Math.E);double F = (int)(Math.exp(1)*100000)/100000.0;double G = (int)Math.max(2, Math.min(3, 4));double H = (int)Math.rint(-2.5);double I = (int)Math.ceil(-2.5);double J = (int)Math.floor(-2.5);int K = (int)Math.round(-2.5f);int L = (int)Math.round(-2.5);double M = (int)Math.rint(2.5);double N = (int)Math.ceil(2.5);double O = (int)Math.floor(2.5);int P = (int)Math.round(2.5f);int Q = (int)Math.round(2.5);int R = (int)Math.round(Math.abs(-2.5));System.out.println(A +" "+ B +" "+ C +" "+ D +" "+ E +" "+ F +" "+ G +" "+ H +" "+ I +" "+ J +" "+ K +" "+ L +" "+ M +" "+ N +" "+ O +" "+ P +" "+ Q +" "+ R);}}6.9import javax.swing.JOptionPane;public class Array{public static void main (String[] args){String incomeString = JOptionPane.showInputDialog("Enter the number of array size:");int income = Integer.parseInt(incomeString);int arraySize = income;int [] myList = new int [arraySize];int m;for ( m = 0; m < arraySize; m++){String elementString = JOptionPane.showInputDialog("Enter the " + (m + 1) + " element of the array");int element = Integer.parseInt(elementString);myList[m] = element;}int minElement = myList[0];for (int i=1; i < arraySize; i++){if (myList[i] < minElement)minElement = myList[i];}JOptionPane.showMessageDialog(null,"The min element is: " + minElement); }}。
java语言程序设计基础篇复习题答案
java语言程序设计基础篇复习题答案【篇一:《java语言程序设计基础教程》(龚永罡_陈昕)习题答案】txt>1.9 练习思考题1、a,b,c2、d3、a,b 4 a 5、b6、开发与运行java程序需要经过的三个主要步骤为____________、____校验________和___解释执行____。
7、如果一个java applet源程序文件只定义有一个类,该类的类名为myapplet,则类myapplet必须是类的子类并且存储该源程序文件的文件名为。
8、如果一个java applet程序文件中定义有3个类,则使用sun 公司的jdk编译器编译该源程序文件将产生___3___个文件名与类名相同而扩展名为__class____的字节码文件。
11、编写一个简单的java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习java”和“we are students”。
解答:class myfirstjava{public static void main(string args[]){system.out.println(“你好,很高兴学习java”);system.out.println(“we are students”);}}第2章 java基本的程序设计结构2.7练习思考题1、a,b,d2、C3、a4、b5、d6、d,f7、b8、d9、d10、a11、D12、a 13、B 14、c15、d16、a17、在java的基本数据类型中,char型采用unicode编码方案,每个unicode码占用字节内存空间,这样,无论是中文字符还是英文字符,都是占用字节内存空间。
18、设 x = 2 ,则表达式 ( x + + )/3 的值是。
19、若x = 5,y = 10,则x y和x = y的逻辑值分别为和。
20、设有数组定义:int myintarray[] = { 10, 20, 30, 40, 50, 60, 70 };则执行以下几个语句后的输出结果是: 120。
Java语言程序设计(基础篇)原书第十一版梁勇第9章课后题答案
Java语⾔程序设计(基础篇)原书第⼗⼀版梁勇第9章课后题答案9.1设计⼀个名为Rectangle的类表⽰矩形public class Test{public static void main(String[] args) {Rectangle rectangle1=new Rectangle(4,40);System.out.println("矩形的宽是"+rectangle1.width+",⾼是"+rectangle1.height+",⾯积是"+rectangle1.getArea()+",周长是"+rectangle1.getPerimeter());Rectangle rectangle2=new Rectangle(3.5,35.9);System.out.print("矩形的宽是"+rectangle2.width+",⾼是"+rectangle2.height+",⾯积是"+rectangle2.getArea()+",周长是"+rectangle2.getPerimeter());}}class Rectangle{double width=1;double height=1;Rectangle(){}Rectangle(double newWidth,double newHeight){width=newWidth;height=newHeight;}double getArea(){return width*height;}double getPerimeter(){return (width+height)*2;}9.3使⽤Date类public class Test {public static void main(String[] args) {Date date = new Date();long l=10000;for(int i = 1; i <9; i++) {date.setTime(l);printDate(l, date);l*=10;}}public static void printDate(long l, Date date) { System.out.println(l + ": " + date.toString());}}9.4使⽤Random类public class Test {public static void main(String[] args) { Random random=new Random(1000);for (int i=1;i<51;i++){System.out.print(random.nextInt(100)+"\t");if (i%10==0){System.out.println();}}}}9.6秒表public class Test {public static void main(String[] args) {StopWatch stopWatch=new StopWatch();stopWatch.start();int[] a = new int[100000];for (int i=0;i<100000;i++){a[i]=(int)(Math.random()*200);}count(a);stopWatch.stop();System.out.print("测试所⽤时间为:"+stopWatch.getElapsedTime()+"ms"); }public static void count(int[] a){int max ;int tmp ;for(int i=0;imax = i;for(int j=i+1;jif(a[max]max = j;}if(i!=max){tmp = a[i]; a[i] = a[max]; a[max] = tmp;}}}}class StopWatch {private long startTime;private long endTime;StopWatch(){startTime = System.currentTimeMillis();}public void start(){startTime = System.currentTimeMillis();}public void stop(){ Array endTime = System.currentTimeMillis();}public long getElapsedTime(){return endTime - startTime;}}9.7 Accont类public class DemoA {public static void main(String[] args) {Account account=new Account();Scanner in=new Scanner(System.in);System.out.println("创建⽤户,依次输⼊id、balance、annualInterestRate:"); int id=in.nextInt();double balance=in.nextDouble();double annualInterestRate=in.nextDouble();account.ChuangJian(id,balance,annualInterestRate);System.out.print("请输⼊取款额:");int money=in.nextInt();account.withDraw(money);System.out.print("请输⼊存款额:");money=in.nextInt();account.deposit(money);account.Print();}}class Account{private int id;private double balance;private double annualInterestRate;private Date dateCreated;public void Print(){System.out.println("余额为:"+balance);System.out.println("⽉利息为:"+getMonthlyInterset());System.out.print("开户⽇期为:");getDate();}public void ChuangJian(){id=0;balance=0;annualInterestRate=0;}public void ChuangJian(int id,double balance,double annualInterestRate){ this.id=id;this.balance=balance;this.annualInterestRate=annualInterestRate;this.dateCreated = new Date();}public void Look(){System.out.println("id:"+id);System.out.println("balance:"+balance);System.out.println("annualInterestRate:"+annualInterestRate);}public void Change(int id){System.out.println("请输⼊更改后的id、balance、annualInterestRate"); Scanner in=new Scanner(System.in);this.id=in.nextInt();this.balance=in.nextDouble();this.annualInterestRate=in.nextDouble();}public Date getDate(){System.out.println(dateCreated);return dateCreated;}public double getMonthlyInterestRate(){ return annualInterestRate/12;}public double getMonthlyInterset(){ return getMonthlyInterestRate()*balance; }public void withDraw(int moneyOut){ balance-=moneyOut;}public void deposit(int moneyIn){ balance+=moneyIn;}}9.8 Fan类public class DemoB {public static void main(String[] args) { Fan fan1=new Fan();fan1.setSpeed(3);fan1.setRadius(10);fan1.setColor("yellow");fan1.setOn(true);System.out.println("fab1:"+fan1.toString()); Fan fan2=new Fan();fan2.setSpeed(2);fan2.setRadius(5);fan2.setColor("blue");fan2.setOn(false);System.out.println("fab2:"+fan2.toString()); }}class Fan{int SLOW=1;int MEDIUM=2;int FAST=3;private int speed=SLOW;private boolean on=false;private double radius=5;String color="blue";public Fan(){}public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public boolean isOn() {return on;}public void setOn(boolean on) {this.on = on;}public double getRadius() {return radius;}public void setRadius(double radius) {this.radius = radius;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public String toString(){if (on){return getSpeed()+"\t"+getColor()+"\t"+getRadius();return "fan is off"+"\t"+getColor()+"\t"+getRadius();}}}9.11代数:2×2的线性⽅程public class DemoC {public static void main(String[] args) {LinearEquation linearEquation1=new LinearEquation(9,4,3,-5,-6,-21);if (linearEquation1.isSolvable()){System.out.println("X是:"+linearEquation1.getX()+",\tY是:"+linearEquation1.getY()); }else System.out.print("The equation has no solution");LinearEquation linearEquation2=new LinearEquation(1,2,2,4,4,5);if (linearEquation2.isSolvable()){System.out.print("X是:"+linearEquation2.getX()+",\tY是:"+linearEquation2.getY()); }else System.out.print("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 a,double b,double c,double d,double e,double f){ this.a=a;this.b=b;this.c=c;this.d=d;this.e=e;this.f=f;}public double getA() {}public double getB() { return b;}public double getC() { return c;}public double getD() { return d;}public double getE() { return e;}public double getF() { return f;}public boolean isSolvable(){ if (a*d-b*c!=0){return true;}else return false;}public double getX(){ return (e*d-b*f)/(a*d-b*c);}public double getY(){ return (a*f-e*c)/(a*d-b*c);}}。
《Java程序设计案例教程》第九章练习答案
第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)。
《Java语言程序设计:基础篇》课后复习题答案-第九章
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.。
Java程序设计基础与实战-习题答案(人邮) 第9章作业参考答案
第9章作业参考答案1.填空题Component MenuComponent(1)WindowListenerFlowLayout(2)AWT(5)事件事件源事件监听器2.选择简答题(1)回答要点•awt是基于本地方法的C/C++程序,其运行速度比拟快;而swing是基于awt的Java程序,其运行速度比拟慢。
•AWT的控件在不同的平台可能表现不同,而Swing在所有平台表现一致。
•AWT和Swing的实现原理不同。
•AWT的图形函数与操作系统提供的图形函数有着一一对应的关系;而Swing不仅提供了AWT的所有功能,还用纯粹的Java代码对AWT的功能进行了大幅度的扩充。
•awt是抽象窗口组件工具包,是java最早的用于编写图形节目应用程序的开发包(2)回答要点在java.awt包中提供了5中常用的布局管理器,分别式FlowLayouK流式布局管理器)、BorderLayout (边界布局管理器)、GridLayout (网格布局管理器)、GridBagLayout(网格包布局管理器)和CradLayout (卡片布局管理器)(3)回答要点事件处理机制专门用于响应用户的操作,比方,想要响应用户的点击鼠标、按下键盘等操作,就需耍使用AWT的事件处理机制。
AWT事件处理机制中几个比拟重要的概念如下所示:•事件对象(Event):封装了GUI组件上发生的特定事件(通常就是用户的一次操作)事件源(组件):事件发生的场所,通常就是产生事件的组件。
•监听器(Listener):负责监听事件源上发生的事件,并对各种事件做出响应处理的对象(对象中包含事件处理器)。
•事件处理器:监听器对象对接收的事件对象进行相应处理的方法。
(4)回答要点通过实现XxxListener接口或者继承XxxAdapter类实现一个事件监听器类,并对处理监听动作的方法进行重写1创立事件源对象和事件监听器对象1调用事件源的addXxxLisntener()方法,为事件源注册事件监听器对象(5)回答要点JavaAWT里面的事件可以简单的分为窗体事件(WindowEvent),鼠标事件(MouseEvent), 键盘事件(KeyEvent),动作事件(ActionEvent)等事件。
Java语言程序设计(郑莉)第九章课后习题答案要点
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,该程序请求用户输入圆的半径,然后显示该圆的直径、周长和面积。
Java龚永罡答案
《Java语言程序设计基础教程》上机实验指导手册实验一 Java环境演练【目的】①安装并配置Java运行开发环境;②掌握开发Java应用程序的3个步骤:编写源文件、编译源文件和运行应用程序;③掌握开发Java Applet程序的3个步骤:编写源文件、编译源文件和运行Java Applet 程序;④学习同时编译多个Java源文件。
【内容】1.一个简单的应用程序✧实验要求:编写一个简单的Java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习Java”和“We are students”。
✧程序运行效果示例:程序运行效果如下图所示:✧程序模板:Hello.javapublic class Hello{public static void main (String args[ ]){【代码1】 //命令行窗口输出"你好,很高兴学习Java"A a=new A();a.fA();}}class A{void fA(){【代码2】 //命令行窗口输出"We are students"}}✧实验后的练习:1.编译器怎样提示丢失大括号的错误?2.编译器怎样提示语句丢失分号的错误?3.编译器怎样提示将System写成system这一错误?4.编译器怎样提示将String写成string这一错误?2.一个简单的Java Applet程序✧实验要求:编写一个简单的Java Applet程序,并在Java Applet中写两行文字:“这是一个Java Applet程序”和“我改变了字体”。
✧程序运行效果示例:程序运行效果如下图所示:✧程序模板:FirstApplet.javaimport java.applet.*;import java.awt.*;public class FirstApplet extends Applet{public void paint(Graphics g){g.setColor(Color.blue);【代码1】//在Java Applet中绘制一行文字:“这是一个Java Applet 程序”g.setColor(Color.red);g.setFont(new Font("宋体",Font.BOLD,36));【代码2】//在Java Applet中绘制一行文字:“我改变了字体”}}✧实验后的练习:5.程序中的主类如果不用public修饰,编译能通过吗?6.程序中的主类如果不用public修饰,程序能正确运行吗?7.程序将paint方法误写成Paint,编译能通过么?8.程序将paint方法误写成Paint,运行时能看到有关的输出信息吗?3.联合编译✧实验要求:编写4个源文件:Hello.java、A.java、B.java和C.java,每个源文件只有一个类,Hello.java是一个应用程序(含有main方法),使用了A、B和C类。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
《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;}}。