java语言程序设计基础篇第十版课后答案第二章答案
- 格式:docx
- 大小:12.67 KB
- 文档页数:3
第一章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);}}。
public class xiti9{public static void main(String args[]) {int x=4;int y;if(x<1){y=x;}else if(x>=10){y=4*x;}else{y=3*x-2;}System.out.println("y="+y);}}习题12public class xiti12{public static void main(String args[]) {int sum=0;for(int k=1;k<=10;k++){sum=sum+k*k;}System.out.println("sum="+sum); }}习题13public class xiti13{public static void main(String args[]) {intt,a=3,b=5,c=8;if(a<b){t=a;a=b;b=t;}if(a<c){t=a;a=c;c=t;}{t=b;b=c;c=t;}System.out.println("大小顺序输出为:"+a+" "+b+" "+c); }}习题14public class xiti14{public static void main(String args[]){int n=1;System.out.print("\n1-100之间的所有素数为:\n"+" 3"); for(int i=1;i<=100;i++){for(int j=2;j<=i/2;j++){if(i%j==0){break;}if(j==i/2){System.out.print(" "+i);n++;}}}System.out.println("\n共有"+n+"个素数。
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语言程序设计课后习题答案全集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语言程序设计(郑莉)第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包括现实世界物体特征的抽象实体,它反映系统为之保留信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方式的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)二者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方式?它有那些大体特征?答:面向对象程序设计从所处置的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3.在下面的应用中,找出可能用到的对象,对每一个对象,列出可能的状态和行为。
1)模拟航空预订系统交易的程序2)模拟银行交易的程序答:1)航空预订交易:状态:旅客姓名,身份证号,联系号码,起身地址,抵达地址,起身日期。
行为:订票,领票,买票,退票。
2)银行交易:状态:客户姓名,账号,身份证号。
行为:存款,取款,汇款。
4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方式、实例属性及其区别。
答:实例方式表示特定对象的行为,在声明时前面不加static修饰符,在利历时需要发送给一个类实例。
类方式也称为静态方式,在方式声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方式可以直接访问实例变量,挪用实例方式,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默许类)两种。
第一章课后习题1.编译Java程序的命令是什么?2.执行Java程序的命令是什么?3.Java应用程序和小程序的区别是什么?4.编写一个application ,实现在屏幕上打印自己名字的功能。
第一章课后习题答案1.编译Java程序的命令是什么?答案:javac 源文件名2.执行Java程序的命令是什么?java 主类名3.Java应用程序和小程序的区别是什么?Java application⏹由Java解释器独立运行字节码⏹由专门的命令行启动程序执行⏹程序中有定义了main()方法的主类Java applet⏹不能独立运行,字节码必须嵌入HTML文档⏹当浏览器调用含applet的Web页面时执行⏹程序中含有java. applet. Applet 类的子类4.编写一个application ,实现在屏幕上打印自己名字的功能。
class Test{public static void main(String[] args){System.out.println(“张三”);}}第二章课后习题(1)一、选择题1.下列变量定义错误的是。
A) int a; B) double b=4.5; C) boolean b=true; D)float f=9.8;2.下列数据类型的精度由高到低的顺序是:a)float,double,int,longb)double,float,int,bytec)byte,long,double,floatd)double,int,float,long3.执行完下列代码后,int a=3;char b='5';char c=(char)(a+b);c的值是?A)’8’ b)53 c)8 d)564.Unicode是一种_____________A) 数据类型 B)java包 C)字符编码 D)java类5.6+5%3+2的值是___________A)2 B)1 C) 9 D)106.下面的逻辑表达式中合法的是__________A)(7+8)&&(9-5) B)(9*5)||(9*7) C)9>6&&8<10 D)(9%4)&&(8*3) 7.java语言中,占用32位存储空间的是__________。
第2章1.Java语言有哪些主要特点。
平台独立性安全性多线程网络化面向对象2.目前美国Sun公司提供的适用不同开发规模的JDK有哪些。
目前Sun共提供了三种不同的版本:微平台版J2ME(Java 2 Platform Micro Edition),标准版J2SE(Java 2 Platform Standard Edition)和企业版J2EE(Java 2 Platform Enterprise Edition),这三种版本分别适用于不同的开发规模和类型,对于普通Java开发人员和一般学习者来说,选用标准版J2SE就可以了,学会了J2SE,再学J2ME或J2EE就比较容易上手,因为它们之间虽有所侧重,但相似之处很多,尤其是语言本身是一样的,都是Java。
3.Java Application的开发步骤有哪些。
Java Application的开发步骤:(1)下载JDK软件并安装;(2)配置相应的环境变量(path和classpath);(3)编写Java源程序(文本编辑器或集成开发环境IDE);(4)编译Java源程序,得到字节码文件(javac *.java);(5)执行字节码文件(java 字节码文件名)。
4.什么是环境变量,设置环境变量的主要目的是什么。
环境变量的配置主要是为了进行“寻径”,也即让程序能找到它需要的文件,所以设置的内容就是一些路径。
5.不参考书本,试着编写一个简单的Java Application程序,实现在Dos窗口输出“Welcome to Nanjing City!”字符串。
并对该程序进行编译和运行。
public class Hello {public static void main(String args[]){System.out.println("Welcome to Nanjing City!");}}6.编写一个Java Application程序,实现分行显示字符串“Welcome to Nanjing City”中的四个单词。
AnjoyoJava10课后习题带答案以下是为大家整理的AnjoyoJava10课后习题带答案的相关范文,本文关键词为AnjoyoJava10,课后,习题,答案,AnjoyoJa,您可以从右上方搜索框检索更多相关文章,如果您觉得有用,请继续关注我们并推荐给您的好友,您可以在综合文库中查看更多范文。
AnjoyoJava10课后习题一、选择题:1.下列哪一个是计算机的联网不可以实现的功能()。
A、使用远程资源b、共享信息、程序和数据c、分布处理D、共享硬件2.下列哪个不属于计算机网络按照网络拓扑结构可以分为()的网络类型。
A、星型网络b、光导纤维c、总线网络D、环线网络3.下列关于网络工作模式说法不正确的是()A、专用服务器结构,由若干台微机工作站与一台或多台文件服务器通过通信线路连接起来组成工作站存取服务器文件。
b、客户机/服务器模式,这种典型的用法是银行pos机。
c、客户机/服务器模式,其中一台或几台较大的计算机集中进行共享数据库的管理和存取,称为服务器。
D、对等式网络中没有专用服务器,每一个工作站既可以起客户机作用也可以起服务器作用。
4.下列关于osI参考模型的说法不正确的是()A、数据链路层是最底层,它是网络硬件设备之间的接口。
b、网络层通过网络连接交换网络服务数据单元。
c、会话层提供两个进程间的连接管理功能。
D、应用层是直接面对用户的一层,提供osI用户服务。
5.下列关于Tcp协议说法错误的是()A、Tcp协议它为两台计算机之间的连接起了重要作用。
b、Tcp协议会让它们建立一个连接、发送和接收数据以及终止连接。
c、Tcp协议被称作一种不可靠的端对端协议。
D、Tcp重发一切没有收到的数据,进行数据内容准确性检查并保证分组的正确顺序。
6.下列关于Ip协议说法错误的是()。
A、Internet上的所有数据通过Ip包的方式传输。
b、如果希望能在Internet上进行交流和通信,每台连上Internet的计算机都必须遵守Ip协议。
《Java语言程序设计(基础篇)》(第10版梁勇著)第二十一章练习题答案21.1import java.util.*;public class Exercise21_01 {public static void main(String[] args) {LinkedHashSet<String> set1 = new LinkedHashSet<String>(Arrays.asList( new String[]{"George", "Jim", "John", "Blake", "Kevin", "Michael"}));LinkedHashSet<String> set1Clone1 = (LinkedHashSet<String>)set1.clone(); LinkedHashSet<String> set1Clone2 = (LinkedHashSet<String>)set1.clone();LinkedHashSet<String> set2 = new LinkedHashSet<String>(Arrays.asList( new String[] {"George", "Katie", "Kevin", "Michelle", "Ryan"}));set1.addAll(set2);set1Clone1.removeAll(set2);set1Clone2.retainAll(set2);System.out.println("The union of the two sets is " + set1);System.out.println("The difference of the two sets is " + set1Clone1); System.out.println("The intersection of the two sets is " + set1Clone2); }}21.1附加import java.util.*;public class Exercise21_01Extra {public static void main(String[] args) {System.out.print("Enter a string: ");Scanner input = new Scanner(System.in);String s = input.nextLine();Character[] list1 = {'A', 'E', 'I', 'O', 'U'};Set<Character> vowels = new HashSet<>(Arrays.asList(list1));Set<Character> vowelsInString = new HashSet<>();Set<Character> consonantsInString = new HashSet<>();int numbeOfVowels = 0;int numbeOfConsonants = 0;for (int i = 0; i < s.length(); i++) {char ch = Character.toUpperCase(s.charAt(i));if (Character.isLetter(ch)) {if (vowels.contains(ch)) {if (!vowelsInString.contains(ch)) {vowelsInString.add(ch);numbeOfVowels++;}}else if (!consonantsInString.contains(ch)) {consonantsInString.add(ch);numbeOfConsonants++;}}}System.out.println("The number of vowels is " + numbeOfVowels);System.out.println("The number of consonants is " + numbeOfConsonants); }}21.2import java.util.*;import java.io.*;public class Exercise21_02 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_02 fullfilename");System.exit(1);}String filename = args[0];// Create a tree set to hold the wordsTreeSet<String> treeSet = new TreeSet<String>();try {Scanner in = new Scanner(new File(filename));String line;while ((line = in.nextLine()) != null) {String[] tokens = line.split("[ |\n|\t|\r|.|,|)|(|-|\"]");for (int i = 0; i < tokens.length; i++)treeSet.add(tokens[i]);}}catch (Exception ex) {System.err.println(ex);}// Get an iterator for the setIterator iterator = treeSet.iterator();// Display mappingsSystem.out.println("\nDisplay words in ascending order ");while (iterator.hasNext()) {System.out.println(iterator.next());}}}21.3import java.util.*;import java.io.*;public class Exercise21_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise21_03 file.java");System.exit(1);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte","goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);String[] tokens = text.split("[ \\[,()\\]]");for (String token: tokens) {if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");end = text.indexOf("*/");}return text;}}/** This is an incorrect version. It does not count the case such as (this. Here the this keyword* is not counted. It does not exclude keywords in the comments*import java.util.*;import java.io.*;public class Exercise20_03 {public static void main(String[] args) {// Check usageif (args.length != 1) {System.out.println("Usage: java Exercise20_03 file.java");System.exit(0);}// Array of all Java keywords + true + nullString[] keywordString = {"abstract", "finally", "public","boolean", "float", "return", "break", "for", "short", "byte", "goto", "static", "case", "if", "super", "catch", "implements", "switch", "char", "import", "synchronized", "class","instanceof", "this", "const", "int", "throw", "continue","interface", "throws", "default", "long", "transient", "do","native", "try", "double", "new", "void", "else", "package","volatile", "extends", "private", "while", "final","protected", "true", "null"};Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));int count = 0;try {Scanner input = new Scanner(new File(args[0]));while (input.hasNext()) {String token = input.next();if (keywordSet.contains(token))count++;}System.out.println("The number of keywords in the program is " + count);}catch (Exception ex) {ex.printStackTrace();}}}*/21.4import java.util.Scanner;import java.util.HashSet;import java.util.Arrays;public class Exercise21_04 {public static void main(String[] args) throws Exception {HashSet<Character> set1 = new HashSet<Character>(Arrays.asList( new Character[]{'A', 'E', 'I', 'O', 'U'}));System.out.print("Enter a filename: ");Scanner input = new Scanner(System.in);String filename = input.nextLine();input = new Scanner(new java.io.File(filename));int countVowels = 0;int countConsonants = 0;while (input.hasNext()) {String s = input.nextLine().toUpperCase();for (int i = 0; i < s.length(); i++) {if (set1.contains(s.charAt(i)))countVowels++;else if (Character.isLetter(s.charAt(i)))countConsonants++;}}System.out.println("The number of vowels is " + countVowels + " and consonanats is " +countConsonants);}}21.5/*** Usage: Copy this class to the folder, run it with java JavaToHTMLftim * to generate* HTM file for all the .java file in this folder. The generated .htm files are* stored in the same folder*/import java.util.*;import java.io.*;public class Exercise21_05 {// Array of all Java keywords + true + false + nullstatic String[] keywordString = {"abstract", "assert", "boolean","break", "byte", "case", "catch", "char", "class", "const","continue", "default", "do", "double", "else", "enum","extends", "for", "final", "finally", "float", "goto", "if","implements", "import", "instanceof", "int", "interface","long", "native", "new", "package", "private", "protected","public", "return", "short", "static", "strictfp", "super","switch", "synchronized", "this", "throw", "throws","transient", "try", "void", "volatile", "while","true", "false", "null"};static Set<String> keywordSet =new HashSet<String>(Arrays.asList(keywordString));/** Main method */public static void main(String[] args) throws Exception {// Check usageif (args.length != 2) {System.out.println("Usage: java Exercise20_10 javaSourcefile htmlfile");System.exit(1);}Scanner input = new Scanner(new File(args[0]));PrintWriter output = new PrintWriter(new File(args[1]));JavaToHTML(input, output);}static boolean stringToken = false;static String inputFileName;public static void JavaToHTML(Scanner input, PrintWriter output) { try {output.format("%s\r\n", "<html>");output.format("%s\r\n", "<head>");output.format("%s\r\n","<title>Intro to Java Programming, 6E - " + inputFileName +"</title>");output.format("%s\r\n","<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">");output.format("%s\r\n", "<style type = \"text/css\">");output.format("%s\r\n","body {font-family: \"Courier New\", sans-serif; font-size: 100%; color: black}");output.format("%s\r\n",".keyword {color: #000080; font-weight: bold}");output.format("%s\r\n", ".comment {color: #008000}");output.format("%s\r\n", ".literal {color: #0000ff}");// Match the color in the text// output.format("%s\r\n", ".keyword {color: black; font-weight: bold}");// output.format("%s\r\n", ".comment {color: #77797C}");// output.format("%s\r\n", ".literal {color: #007346; font-weight: bold}");output.format("%s\r\n", "</style>");output.format("%s\r\n", "</head>");output.format("%s\r\n", "<body>");output.format("%s\r\n", "<pre>");String text = "";String temp;// Read all lineswhile (input.hasNext()) {temp = input.nextLine();text += temp + "\r\n";}text = text.replaceAll(">", ">");text = text.replaceAll("<", "<");translateToHTML(text, input, output);output.format("%s\r\n", "</pre>");output.format("%s\r\n", "</body>");output.format("%s\r\n", "</html>");}catch (Exception ex) {System.out.println(ex);}finally {try {input.close();output.close();}catch (Exception ex) {}}}/** Translate Java source code to HTML */static void translateToHTML(String text, Scanner input, PrintWriter output) throws Exception {text = text.replaceAll("// ", "LINECOMMENT");text = text.replaceAll("/\\*", "BLOCKCOMMENT");String token;while (text != null && text.length() > 0) {// * and / are in conflict with /* and //String[] parts = text.split("[%\\+\\-\\*/\r\n\t \\[\\].;(){},]", 2); token = parts[0];if (token.length() > 1 && token.startsWith("LINECOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\r\n", 2);text = parts[1];output.format("%s", parts[0].replaceAll("LINECOMMENT", "// "));output.format("%s", "</span>\r\n");continue;}else if (token.length() > 1 && token.startsWith("BLOCKCOMMENT")) {output.format("%s", "<span class = \"comment\">");parts = text.split("\\*/", 2);text = parts[1];output.format("%s", parts[0].replaceAll("BLOCKCOMMENT", "/*") +"*/");output.format("%s", "</span>");continue;}else if (token.length() > 1 && token.matches("'\\w'*")) {output.format("%s", "<span class = \"literal\">");output.format("%s", token);output.format("%s", "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("'") && token.endsWith("'") &&(token.length() > 1)) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.equals("' '")) {output.format("%s", "<span class = \"literal\">" + token+ "</span>");}else if (token.startsWith("\"") && token.endsWith("\"") &&(token.length() == 1)) {if (stringToken) {output.format("%s", token + "</span>");stringToken = false;}else {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}}else if (token.startsWith("\"")) {output.format("%s", "<span class = \"literal\">" + token); stringToken = true;}else if (token.endsWith("\"") && (!token.endsWith("\\\""))) { output.format("%s", token);output.format("%s", "</span>");stringToken = false;}else if (token.matches("\\d+")) { // Check if numericoutput.format("%s", "<span class = \"literal\">" + token +"</span>");}else if (!stringToken && keywordSet.contains(token)) {output.format("%s", "<span class = \"keyword\">" + token +"</span>");}else {output.format("%s", token);}if (token.length() < text.length()) {if (text.charAt(token.length()) == '<')output.format("%s", "<");else if (text.charAt(token.length()) == '>')output.format("%s", ">");elseoutput.format("%s", text.charAt(token.length()));}if (parts.length == 2) {text = parts[1];}}}}21.6import java.util.*;public class Exercise21_06 {public static void main(String[] args) {// Create a tree map to hold words and key and count as value TreeMap<Integer, Integer> treeMap = new TreeMap<>();Scanner input = new Scanner(System.in);while (true) {// Enter an integerSystem.out.print("Enter an integer: ");int number = input.nextInt();if (number == 0) break;Integer key = new Integer(number);if (treeMap.get(key) != null) {int value = ((Integer)treeMap.get(key)).intValue();value++;treeMap.put(key, new Integer(value));}else {treeMap.put(key, new Integer(1));}}Integer max = Collections.max(treeMap.values());Set<Integer> keys = treeMap.keySet();Iterator<Integer> iterator = keys.iterator();while (iterator.hasNext()) {Object key = iterator.next();Integer value = (Integer)(treeMap.get(key));if (value.equals(max)) {System.out.println("Number " + key + " occurred most");}}}}21.7import java.util.*;public class Exercise21_07 {public static void main(String[] args) {// Text in a stringString text = "Have a good day. Have a good class. " + "Have a good visit. Have fun!";// Create a hash map to hold words and key and count as value HashMap<String, Integer> hashMap = new HashMap<>();String[] tokens = text.split("[ |.|!|?]");for (String key: tokens) {if (hashMap.get(key) != null) {hashMap.put(key, hashMap.get(key).intValue() + 1);}else {if (key.trim().length() > 0)hashMap.put(key, 1);}}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();ArrayList<WordOccurrence> list = new ArrayList<>();for (Map.Entry<String, Integer> entry: entrySet) {list.add(new WordOccurrence(entry.getKey(), entry.getValue())); }Collections.sort(list);for (WordOccurrence item: list) {System.out.println(item);}}}class WordOccurrence implements Comparable<WordOccurrence> {String word;int count;public WordOccurrence(String word, int count) {this.word = word;this.count = count;}@Overridepublic int compareTo(WordOccurrence o) {return count - o.count;}@Overridepublic boolean equals(Object o) {return word.equals(((WordOccurrence)o).word);}@Overridepublic String toString() {return word + ": " + count;}}21.8import java.util.*;import java.io.*;public class Exercise21_08 {public static void main(String[] args) {if (args.length != 1) {System.out.println("Usage: java Exercise21_08 fullfilename");System.exit(1);}String filename = args[0];// Create a tree map to hold words as key and count as valueTreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();try {Scanner input = new Scanner(new File(filename));while (input.hasNext()) {String line = input.nextLine();String[] words = line.split("[ @!~{}\\[\\]$#^&*\n\t\r.,;?'\")(]");for (int i = 0; i < words.length; i++) {if (words[i].trim().length() > 0 &&words[i].trim().matches("[A-Z|a-z]+")) {String key = words[i].toLowerCase();if (treeMap.get(key) != null) {int count = treeMap.get(key);count++;treeMap.put(key, count);}else {treeMap.put(key, 1);}}}}}catch (Exception ex) {ex.printStackTrace();}// Get an entry set for the tree mapSet<Map.Entry<String, Integer>> entrySet = treeMap.entrySet();// Display words in alphabetical orderSystem.out.println("\nDisplay words and their count in " + " ascending order of the words");for (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); }}21.9import java.util.*;public class Exercise21_09 {public static void main(String[] args) {String[][] stateCapital = {{"Alabama", "Montgomery"},{"Alaska", "Juneau"},{"Arizona", "Phoenix"},{"Arkansas", "Little Rock"},{"California", "Sacramento"},{"Colorado", "Denver"},{"Connecticut", "Hartford"},{"Delaware", "Dover"},{"Florida", "Tallahassee"},{"Georgia", "Atlanta"},{"Hawaii", "Honolulu"},{"Idaho", "Boise"},{"Illinois", "Springfield"},{"Indiana", "Indianapolis"},{"Iowa", "Des Moines"},{"Kansas", "Topeka"},{"Kentucky", "Frankfort"},{"Louisiana", "Baton Rouge"},{"Maine", "Augusta"},{"Maryland", "Annapolis"},{"Massachusettes", "Boston"},{"Michigan", "Lansing"},{"Minnesota", "Saint Paul"},{"Mississippi", "Jackson"},{"Missouri", "Jefferson City"},{"Montana", "Helena"},{"Nebraska", "Lincoln"},{"Nevada", "Carson City"},{"New Hampshire", "Concord"},{"New Jersey", "Trenton"},{"New York", "Albany"},{"New Mexico", "Santa Fe"},{"North Carolina", "Raleigh"},{"North Dakota", "Bismark"},{"Ohio", "Columbus"},{"Oklahoma", "Oklahoma City"},{"Oregon", "Salem"},{"Pennslyvania", "Harrisburg"},{"Rhode Island", "Providence"},{"South Carolina", "Columbia"},{"South Dakota", "Pierre"},{"Tennessee", "Nashville"},{"Texas", "Austin"},{"Utah", "Salt Lake City"},{"Vermont", "Montpelier"},{"Virginia", "Richmond"},{"Washington", "Olympia"},{"West Virginia", "Charleston"},{"Wisconsin", "Madison"},{"Wyoming", "Cheyenne"}};Map<String, String> map = new HashMap<String, String>();for (int i = 0; i < stateCapital.length; i++)map.put(stateCapital[i][0].toLowerCase(), stateCapital[i][1]);Scanner input = new Scanner(System.in);System.out.print("Enter a state: ");String state = input.nextLine().toLowerCase().trim();if (map.containsKey(state))System.out.println("The capital is " +map.get(state));elseSystem.out.println("No such state ");}}21.10import java.util.*;import java.io.*;public class Exercise21_10 {public static void main(String[] args) {// Prompt the user to enter a Java source fileScanner input = new Scanner(System.in);System.out.print("Enter a file name: ");String filename = input.nextLine();// Array of all Java keywords + true + nullString[] keywordString = { "abstract", "finally", "public", "boolean", "float", "return", "break", "for", "short", "byte", "goto", "static","case", "if", "super", "catch", "implements", "switch", "char","import", "synchronized", "class", "instanceof", "this", "const","int", "throw", "continue", "interface", "throws", "default", "long","transient", "do", "native", "try", "double", "new", "void", "else","package", "volatile", "extends", "private", "while", "final","protected", "true", "null" };Set<String> keywordSet = newHashSet<String>(Arrays.asList(keywordString));int count = 0;try {input = new Scanner(new File(filename));String text = "";while (input.hasNext()) {String line = input.nextLine();line = stripLineComments(line);line = stripLineStringLiterals(line);text += line + " ";}text = stripParagraghComments(text);TreeMap<String, Integer> map = new TreeMap<String, Integer>();String[] tokens = text.split("[ \\[,()\\]]");for (String token : tokens) {if (keywordSet.contains(token))if (map.get(token) == null) {map.put(token, 1);} else {int value = map.get(token);value++;map.put(token, value);}}// Get all entries into a setSet<Map.Entry<String, Integer>> entrySet = map.entrySet();// Get key and value from each entryfor (Map.Entry<String, Integer> entry: entrySet)System.out.println(entry.getValue() + "\t" + entry.getKey()); } catch (Exception ex) {ex.printStackTrace();}}/* Strip line comments */private static String stripLineComments(String line) {int index = line.indexOf("//");if (index < 0)return line;elsereturn line.substring(0, index);}/* Strip string literals */private static String stripLineStringLiterals(String line) {int start = line.indexOf("\"");int end = line.indexOf("\"", start + 1);while (start > 0 && end > 0) {line = line.substring(0, start) + line.substring(end + 1);start = line.indexOf("\"");end = line.indexOf("\"");}return line;}/* Strip paragraph comments */private static String stripParagraghComments(String text) {int start = text.indexOf("/*");int end = text.indexOf("*/");while (start > 0 && end > 0) {text = text.substring(0, start) + text.substring(end + 2);start = text.indexOf("/*");。
《Java基础入门》课后习题答案第1章多线程一、填空题1、Thread、Runnable、Callable2、synchronized、this3、NEW(新建状态)、RUNNABLE(可运行状态)、BLOCKED(阻塞状态)、WAITING(等待状态)、TIMED_W AITING(定时等待状态)、TERMINATED(终止状态)4、开启一个新线程、run()方法5、setDaemon(true)、start()二、判断题1、错2、对3、对4、错5、对三、选择题1、AC2、BC3、ABC4、C5、ABCD四、简答题1、一种是继承ng包下的Thread类,覆写Thread类的run()方法,在run()方法中实现运行在线程上的代码。
new Thread() {public void run(){}}.start();另一种就是实现ng.Runnable接口,同样是在run()方法中实现运行在线程上的代码。
class MyThread implements Runnable{public void run(){}}另一种就是实现java.util.concurrent.Callable接口,同样是在call()方法中实现运行在线程上的代码。
class MyThread implements Callable<Object>{public Object call() throws Exception{}}1、调用sleep(long millis)方法,正在执行的线程主动让出CPU去执行其他线程,在sleep(long millis)方法指定的时间过后,CPU才会回到这个线程上继续往下执行,如果当前线程进入了同步锁,sleep(long millis)方法并不会释放锁,即使当前线程使用sleep(long millis)方法让出了CPU,但其他被同步锁挡住了的线程也无法得到执行。
wait()在一个已经进入了同步锁的线程内进行调用,让当前线程暂时让出同步锁,以便其它正在等待此锁的线程可以得到同步锁并运行。
第一章测试1【单选题】(10分)Java属于以下哪种语言?「A.汇编语言「B.机器语言「C.其余选项都不对「D.高级语言参考答案D2【单选题】(10分)下面哪种类型的文件可以在Java虚拟机中运行?()「A..class「B..exe c C.. java r D.【多选题】(8分)Java中的数据类型可以分为两大类,分别是:()和()「A.引用型数据类型「B.整数类型「C.基本数据类型「D.浮点类型参考答案AC9【判断题】(8分)Java语言标识符名称不区分大小写。
「A.对「B.错参考答案B10【判断题】(8分)0xC5表示的是一个十六进制数。
「A.对「B.错参考答案A11【判断题】(10分)continue;语句只用于循环语句中,它的作用是跳出循环。
「A.对「B.错参考答案B12【判断题】(10分)-5%3的运算结果是20「A.B.参考答案A第三章测试1【单选题】(8分)在非静态成员方法中,可以使用关键字()访问类的其他非静态成员。
「A. this 「B. public 「c. super r D. static参考答案A2【单选题】(8分)下面关于类的定义,哪一个是正确的?()「A. publicelassvoidnumber{ //•••)「B.publicclassMOVE(){//•••)c c.publicclassCar{//•••)「D.publicvoidIIH{//…参考答案c3【单选题】(8分)在Java中,针对类和成员提供了4种访问级别,以下控制级别由小到大的顺序是:()O「A.private〈默认<protected<public「B.默认<private<protected<public「C.protected〈默认<private<public「D.protectecKpri vat e〈默认〈public参考答案A4【单选题】(8分)Test类的定义如下:publicclassTest{publicTest(){System. out. printin ("构造方法一被调用了。
《Java语言程序设计基础教程》练习思考题参考答案第1章 Java程序设计概述1.9 练习思考题1、Java运行平台包括三个版本,请选择正确的三项:()A. J2EEB. J2MEC. J2SED. J2E解答:A,B,C2、Java JDK中反编译工具是:()A. javacB. javaC. jdbD. javap解答:D3、public static void main方法的参数描述是:()A. String args[]B. String[] argsC. Strings args[]D. String args解答:A,B4、在Java中,关于CLASSPATH环境变量的说法不正确的是:()A. CLASSPATH一旦设置之后不可修改,但可以将目录添加到该环境变量中。
B. 编译器用它来搜索各自的类文件。
C. CLASSPATH是一个目录列表。
D. 解释器用它来搜索各自的类文件。
解答:A5、编译Java Application源文件将产生相应的字节码文件,扩展名为()A. .javaB. .classC. .htmlD. .exe解答:B6、开发与运行Java程序需要经过的三个主要步骤为____________、____________和____________。
7、如果一个Java Applet源程序文件只定义有一个类,该类的类名为MyApplet,则类MyApplet必须是______类的子类并且存储该源程序文件的文件名为______。
8、如果一个Java Applet程序文件中定义有3个类,则使用Sun公司的JDK编译器编译该源程序文件将产生______个文件名与类名相同而扩展名为______的字节码文件。
9、开发与运行Java程序需要经过哪些主要步骤和过程?10、Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎么样的?11、编写一个简单的Java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习Java”和“We are students”。
package cn.Testcx;import java.util.Scanner;public class lesson2 {public static void main(String[] args){@SuppressWarnings("resource")Scanner input =new Scanner(System.in);System.out.print("请输入一个摄氏温度:");double Celsius =input.nextDouble();double Fahrenheit =(9.0/5)*Celsius+32;System.out.println("摄氏温度:"+Celsius+"度"+"转换成华氏温度为:"+Fahrenheit+"度");System.out.print("请输入圆柱的半径和高:");double radius =input.nextDouble();int higth = input.nextInt();double areas =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.println(feet+"英尺转换成米:"+meters);System.out.print("输入一个磅数:");double pounds =input.nextDouble();double kilograms =pounds*0.454;System.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 =totalCurrentTimeMillis/1000;long currentSeconds =totalSeconds%60;long totalMinutes =totalSeconds/60;long currentMinutes =(totalSeconds%(60*60))/60;long currenthours =(totalMinutes/60)%24;System.out.print("输入时区偏移量:");byte zoneOffset = input.nextByte();long currentHour =(currenthours+(zoneOffset*1))%24;System.out.println("当期时区的时间为:"+currentHour+"时"+currentMinutes+"分"+currentSeconds+"秒");System.out.print("请输入v0,v1,t:");double v0 =input.nextDouble();double v1 =input.nextDouble();double t =input.nextDouble();float a = (float) ((v1-v0)/t);System.out.println("平均加速度a="+a);System.out.println("输入水的重量、初始温度、最终温度:");double water =input.nextDouble();double initialTemperature =input.nextDouble();double finalTemperature = input.nextDouble();double Q =water*(finalTemperature-initialTemperature)*4184;System.out.println("所需热量为:"+Q);System.out.print("输入年数:");int numbers =input.nextInt();long oneYearsSecond =365*24*60*60;Long population= (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 lengthOfAirplane =(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.pow(side, 2)))/2;System.out.println("六边形的面积为:"+area);}}。
第1章计算机、程序和Java概述1.1(显示三条消息)编写程序,显示Welcome to Java、Welcome to Computer Science和Programming is fun。
程序:显示:1.2(显示五条消息)编写程序,显示Welcome to Java五次程序:显示:1.3(显示图案)编写一个程序,显示下面的图案:程序:显示:1.4(打印表格)编写程序,显示以下表格:程序:显示:1.5(计算表达式)编写程序,显示(9.5x4.5-2.5x3)/(45.5-3.5)的结果程序:显示:1.6(数列求和)编写程序,显示1+2+3+4+5+6+7+8+9的结果程序:显示:1.7(近似求π)可以使用以下公式计算π:Π=4x(1-1/3+1/5-1/7+1/9-1/11+1/13+...)编写程序,显示4x(1-1/3+1/5-1/7+1/9-1/11+1/13...)的结果。
在程序中用1.0代替1 程序:显示:第2章基本程序设计2.1(将摄氏温度转换为华氏温度)编写程序,从控制台读入double型的摄氏温度,然后将其转换华氏温度,并显示结果。
转换公式如下所示:Fahrenheit-=(9/5)*celsius+32 (华氏度=(9/5)*摄氏度+32)程序:显示:2.2(计算圆柱体的体积)编写程序,读入圆柱体的半径和高,并使用下列公式计算圆柱体的体积面积=半径x半径xπ体积=面积x高程序:显示:2.3(将英尺转换为米)编写程序,读入英尺数,将其转换为米数并显示结果。
一英尺等于0.305米。
程序:显示:2.4(将磅转换为千克)编写程序,将磅数转换为千克数。
程序提示用户输入磅数,然后转换成千克并显示结果。
1磅等于0.454千克。
程序:显示:2.5(财务应用程序:计算小费)编写一个程序,读入一笔费用与酬金率,就算酬金和总钱数。
例如,如果用户读入10作为费用,15%作为酬金率,计算结果显示酬金为$1.5,总费用为$11.5.程序:显示:2.6(求一个整数各位数的和)编写程序,读取一个在0和1000之间的整数,并将该整数的各位数字相加。
JAVA语言与面向对象程序设计课后习题答案第1章面向对象软件开发概述1.简述面向过程问题求解和面向对象问题求解的异同。
试列举出面向对象和面向过程的编程语言各两种。
请问:面向过程问题解,以具体内容的解题过程为研究和同时实现的主体,其思维特点更吻合于计算机;面向对象的问题解,则就是以d对象‖为主体,d对象‖就是现实世界的实体或概念在计算机逻辑中的抽象化则表示,更吻合于人的思维特点。
面向过程的编程语言:c,pascal,foratn。
面向对象的编程语言:c++,java,c#。
2.详述对象、类和实体及它们之间的相互关系。
尝试从日常碰触至的人或物中抽象化出来对象的概念。
答:面向对象技术中的对象就是现实世界中某个具体的物理实体在计算机逻辑中的映射和体现。
类是同种对象的集合与抽象。
类是一种抽象的数据类型,它是所有具有一定共性的对象的抽象,而属于类的某一个对象则被称为是类的一个实例,是类的一次实例化的结果。
如果类是抽象的概念,如d电视机‖,那么对象就是某一个具体的电视机,如d我家那台电视机‖。
3.对象存有哪些属性?什么就是状态?什么就是犯罪行为?二者之间有何关系?建有对象d学生‖,精义这个对象设计状态与犯罪行为。
答:对象都具有状态和行为。
对象的状态又称作对象的静态属性,主要指对象内部所涵盖的各种信息,也就是变量。
每个对象个体都具备自己专有的内部变量,这些变量的值标明了对象所处的状态。
行为又称为对象的操作,它主要表述对象的动态属性,操作的作用是设置或改变对象的状态。
学生的状态:姓名、性别、年龄、所在学校、所在系别、通讯地址、电话号码、入学成绩等;学生的行为:自我介绍、入学注册、选课、参加比赛等。
4.对象间存有哪三种关系?对象d班级‖与对象d学生‖就是什么关系?对象d学生‖与对象d大学生‖就是什么关系?答:对象间可能存在的关系有三种:包含、继承和关联。
对象d班级‖与对象d学生‖是包含关系。
对象d学生‖与对象d大学生‖是继承关系。
第1章Java概述1.编译java application源程序文件将产生相应的字节码文件,这些字节码文件别的扩展名为.java2.执行一个java程序fristapp的方法是运行java fristapp3.main()方法的返回类型是void4.在java代码中,public static void main方法的参数描述正确的是string args【】,string【】args5.内存的回收程序负责释放无用内存√6.java体系主要分为java ME,Java SE,JavaEE三大块第2章Java基础1.Java语言中,下列标识符错误的是40name2.java变量中,以下不属于引用类型的数据类型是字符型3.double d=5.3E12 ×4.C5.A6.for循环的一般形式为;for(初值;终值;增量),以下对for循环的叙述,正确的是初值和增量都是赋值语句,终值是条件判断语句7.当输入下面选项中3值时,将会输出default8.下面哪种方法能够支持javadoc命令/**…*/9.下面声明一个string类型的数组正确的是string str[]10.下面定义一个整型数组,不合法的是int[][]array=new int[][4];11.给定代码;。
下面叙述正确的是输出的结果为:012.java语言规定,标示符只能由字母,数字美元符$和下划线租成,并且第一个字符不能是数字;java是区分大小写的。
13.表达式1/2*3的计算结果是0;设x=2,则表达式(x++)/3的值是014.数组的长度可以用其属性lengt h获得;创建一个数组对象可以使用new关键字创建第3章面向对象基础1.在java中引用对象变量和对象间有什么关系?引用变量是指向对象的一个指针2.对象是面向对象技术的核心所在,在面向对象程序设计中,对象是累的抽象×3.构造方法何时被调用?创建对象时4.A,B,D5.在java语言中在包p1中包含包p2,类A直接隶属于p1,类B直接隶属于包p2.在类c中要使用类a的方法和类b的方法b,需要选择import p1.*; import p1.p2,*;6.java中,访问修饰符限制最高的是private第4章类之间的关系1.在java中,下面关于类的描述正确的是一个父类可以有多个子类2.在java语言中,类worker是类person的子类,worker的构造方法中有一句“super()”,该语句是调用person的构造法法。
第二章Java语言基础一、简答题1.Java应用程序主类的类头应写为public class 类名,它的主方法的方法头应写为publicstatic void main(String args[]),程序的入口是main方法。
2.应用程序的主类中一定要有main方法。
3.单精度float 双精度double,32位和64位4.基本类型和复合类型。
基本类型包括:整型、浮点类型、布尔类型和字符类型。
复合类型包括:数组、字符串和类类型。
5.true和false6. 37.不可以8.不是9.GC是垃圾收集器。
Java 程序员不用担心内存管理,因为垃圾收集器会自动进行管理。
要请求垃圾收集,可以调用下面的方法之一:System.gc()Runtime.getRuntime().gc()10.short s1 = 1; s1 = s1 + 1;有错,s1是short型,s1+1是int型,不能显式转化为short型。
可修改为s1 =(short)(s1 + 1) 。
short s1 = 1; s1 += 1正确。
11.2<<312.switch(expr1)中,expr1是一个整数表达式。
因此传递给switch 和case 语句的参数应该是int、short、char 或者byte。
long,string 都不能作用于swtich。
二、判断题1.错2.错3.对4.错三、填空题1.方法2.public3. 6 244.false5.return (int)(x*y)6.选择结构7.new8.n%13==09.max=x>y?x:y;10.false11.class (c++)+”\t”四、选择题1. C2. A3. A4. A5. D6. A7. B8. C9. A10. D11. C12. A13. B14. B15. B16. C17. C18. D19. B20. D21. C22. B23. B24. D25. C26. D27. B28. C29. C30. A31. B五、阅读程序,回答下面问题。
package cn.Testcx;
import java.util.Scanner;
public class lesson2 {
public static void main(String[] args){
@SuppressWarnings("resource")
Scanner input =new Scanner(System.in);
System.out.print("请输入一个摄氏温度:");
double Celsius =input.nextDouble();
double Fahrenheit =(9.0/5)*Celsius+32;
System.out.println("摄氏温度:"+Celsius+"度"+"转换成华氏温度为:"+Fahrenheit+"度");
System.out.print("请输入圆柱的半径和高:");
double radius =input.nextDouble();
int higth = input.nextInt();
double areas =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.println(feet+"英尺转换成米:"+meters);
System.out.print("输入一个磅数:");
double pounds =input.nextDouble();
double kilograms =pounds*0.454;
System.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 =totalCurrentTimeMillis/1000;
long currentSeconds =totalSeconds%60;
long totalMinutes =totalSeconds/60;
long currentMinutes =(totalSeconds%(60*60))/60;
long currenthours =(totalMinutes/60)%24;
System.out.print("输入时区偏移量:");
byte zoneOffset = input.nextByte();
long currentHour =(currenthours+(zoneOffset*1))%24;
System.out.println("当期时区的时间为:"+currentHour+"时"+currentMinutes+"分"+currentSeconds+"秒");
System.out.print("请输入v0,v1,t:");
double v0 =input.nextDouble();
double v1 =input.nextDouble();
double t =input.nextDouble();
float a = (float) ((v1-v0)/t);
System.out.println("平均加速度a="+a);
System.out.println("输入水的重量、初始温度、最终温度:");
double water =input.nextDouble();
double initialTemperature =input.nextDouble();
double finalTemperature = input.nextDouble();
double Q =water*(finalTemperature-initialTemperature)*4184;
System.out.println("所需热量为:"+Q);
System.out.print("输入年数:");
int numbers =input.nextInt();
long oneYearsSecond =365*24*60*60;
Long population= (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 lengthOfAirplane =(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.pow(side, 2)))/2;
System.out.println("六边形的面积为:"+area);
}
}。