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语言程序设计基础篇(第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程序设计课后第二章习题程序答案
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+"个素数。
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第二章练习题答案
java第二章练习题答案Java第二章练习题答案Java作为一种广泛应用的编程语言,具有着强大的功能和丰富的库。
学习Java 的过程中,练习题是巩固知识和提高编程能力的重要一环。
在第二章的练习题中,我们将探索一些基本的Java概念和语法。
下面是第二章练习题的答案,希望对大家的学习有所帮助。
1. 问题:什么是Java的标识符?标识符的命名规则是什么?答案:Java的标识符是用来标识变量、方法、类等的名称。
标识符的命名规则如下:- 必须以字母、下划线或美元符号开头;- 可以包含字母、数字、下划线或美元符号;- 大小写敏感;- 不能使用Java的关键字。
2. 问题:Java的八种基本数据类型是什么?答案:Java的八种基本数据类型分别是:- byte:字节型;- short:短整型;- int:整型;- long:长整型;- float:单精度浮点型;- double:双精度浮点型;- char:字符型;- boolean:布尔型。
3. 问题:如何声明一个整型变量并赋初值为10?答案:可以使用以下语句声明一个整型变量并赋初值为10:int num = 10;4. 问题:如何将一个字符串转换为整型?答案:可以使用Integer类的parseInt()方法将一个字符串转换为整型。
示例代码如下:String str = "123";int num = Integer.parseInt(str);5. 问题:如何声明一个常量?答案:可以使用关键字final来声明一个常量。
示例代码如下:final int MAX_NUM = 100;6. 问题:如何使用if-else语句实现条件判断?答案:可以使用if-else语句实现条件判断。
示例代码如下:int num = 10;if (num > 0) {System.out.println("num是正数");} else {System.out.println("num是负数或零");}7. 问题:如何使用for循环实现重复执行某段代码?答案:可以使用for循环实现重复执行某段代码。
Java语言程序设计课后习题--优选包括答案.docx
Java语言程序设计 (郑莉 )第二章习题答案1.什么是对象、类,它们之间的联系答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!3)两者的关系:对象是类的具体实例. 。
2.什么是面向对象的程序设计方法它有那些基本特征答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3(无用)4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种具体含义及其区别。
答:类的访问控制符只有public (公共类)及无修饰符(默认类)两种。
区别:当使用 public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
7类成员的访问控制符有哪几种他们对类成员分别有哪些访问限制的作用答 : 类成员的访问控制符有public,private,protecte及无修饰符.public( 公有的 ): 用 public修饰的成分表示公有的, 也就是它可以被其他任何对象访问( 前提是对累成员所在的类访问有访问权限).Private(保护的 ) :类中限定为private的成员只能被这个类本身访问,在类外不可见。
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程序设计课后习题参考答案1. 介绍在 Java 程序设计课程中,课后习题是帮助学生巩固知识、加深理解和提高编程能力的重要环节。
本文将为大家提供《Java程序设计》课后习题的参考答案,以帮助学生更好地学习和掌握 Java 编程。
2. 基本概念Java 程序设计课后习题涵盖了从基础到高级的各种知识点,包括但不限于变量、数据类型、条件语句、循环语句、数组、类、对象、继承、多态等内容。
通过解答这些习题,学生可以加深对这些概念的理解,并且通过实际操作来巩固他们的编程能力。
3. 习题解答策略当解答课后习题时,以下几个策略可以帮助你更好地理解和解决问题:3.1 仔细阅读题目要求。
确保自己充分理解题目所要求的功能和目标。
3.2 分析问题。
在着手解答问题之前,先理清思路,分析问题的要点和关键部分。
3.3 设计算法。
根据问题的要求,设计一个合适的算法来解决问题。
3.4 编写代码。
用 Java 编程语言将你设计的算法转化为代码实现。
3.5 测试和调试。
对编写的代码进行测试和调试,确保程序能够正常运行,并且得到正确的结果。
4. 习题参考答案示例下面我们将列举几个常见的习题参考答案示例,以帮助大家更好地理解和学习 Java 程序设计:4.1 变量与数据类型:习题要求定义一个整型变量并赋值为10,然后输出该变量的值。
```public class VariableExample {public static void main(String[] args) {int num = 10;System.out.println("变量的值为:" + num);}}```4.2 条件语句:习题要求判断一个数是否是偶数,如果是,则输出“偶数”,否则输出“奇数”。
```public class EvenOddExample {public static void main(String[] args) {int num = 5;if (num % 2 == 0) {System.out.println("偶数");} else {System.out.println("奇数");}}}```4.3 循环语句:习题要求输出1到10之间的所有偶数。
Java语言程序设计(基础篇)(第10版 梁勇著)第二章练习题答案
《Java语言程序设计(基础篇)》(第10版 梁勇 著) 第二章 基本程序设计 练习题答案
本人在自学编程过程中,发现本书答案很难找,找到的要么不完整、要么错误百出,所以我将自己所做的 练习题答案,提供给有需要者,供大家交流。本章答案均为本人一字一字所敲,答案均经过验证,虽为初学者, 但代码均按照书中规范要求书写,如有错误或更好的建议,请指正交流。
// 第二章 P59 练习题2.1 (将摄氏温度转为华氏温度) import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) { // 华氏温度和摄氏温度的转换公式为:华氏温度 = (9/5)*摄氏温度+32 Scanner input = new Scanner(System.in);
System.out.print("Enter the time zone offset to GMT: "); long timeZoneOffset = input.nextLong(); // 此处用long还是int?
long totalMilliseconds = System.currentTimeMillis(); long totalSeconds = totalMilliseconds / 1000; long currentSecond = totalSeconds % 60; long totalMinutes = totalSeconds / 60; long currentMinute = totalMinutes % 60; long totalHours = totalMinutes / 60; long currentHour = totalHours % 24; long hour = currentHour + timeZoneOffset;
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十一章练习题答案
《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语言程序设计基础篇第十版课后答案第二章答案
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);}}。
Java语言程序设计基础篇全习题答案1
1. 2. 3. 4.Chapter 1 Introduction to Computers, Programs, and Java A computer is an electronic device that stores and processes data. A computerincludes both hardware and software. In general, hardware is the physical aspect of the computer that can be seen, and software is the invisible instructions that control the hardware and make it work. The hardware of a computer consists of a CPU,cache, memory, hard disk, floppy disk, monitor, printer, and communication devices. The machine language is a set of primitive instructions built into every computer. Assembly language is a low-level programming language in which a mnemonic is used to represent each of the machine language instructions. The high-level languages are English-like and easy to learn and program.The operating system (OS) is a program that manages and controls a computer’s activities. The examples of OS are Windows 98, NT, 2000, XP, or ME. Windows. Application programs such as an Internet browser and a word processor run on top of an operating system.100 in decimal => 64 in hex100 in decimal => 01100100 in binary4340 in decimal => 10F4 in hex4340 in decimal => 1000011110100 in binary2000 in decimal => 7D0 in hex2000 in decimal => 111110100005.1000011001 in binary => 219 in hex1000011001 in binary => 537 in decimal100000000 in binary => 100 in hex 100000000 in binary => 256 in decimal100111 in binary => 27 in hex 100111 in binary => 39 in decimal 6.FEFA9 in hex => 1044393 in decimalFEFA9 in hex => 11111110111110101001 in binary93 in hex => 147 in decimal 93 in hex => 10010011 in binary 2000 in hex => 8192 in decimal7.8.9.10.11.12.13.14.16.17. 2000 in hex => 10000000000000 in binaryDeveloped by a team led by James Gosling at Sun Microsystems in 1991. Originally called Oak, it became Java in 1995 when it was redesigned for developing Internet applications.Java can run on any platform with a Java Virtual Machine. The minimum requirement is the Java Runtime Environment, free from the .The input is the Java source code and the output is the Java bytecode (if compiled successfully).JBuilder by Borland, Sun ONE Studio by Sun, Café by WebGain, Visual Age for Java by IBM are the tools for developing Java programs, not dialects of Java. These tools make developing Java programs easier and more productive.HTML is a markup language for displaying static Web pages. Java is a full-fledged programming language that can be used to develop dynamic Web pages. The Java programs that run from a Web browser are called applets. Java applets must be embedded in HTML files using the <applet> tag.Keywords have specific meaning to the compiler and cannot be used for other purposes in the program such as variables or method names. Examples of keywords are class, static, and void.Java source code is case sensitive. Java keywords are always in lowercase.The source file extension is .java and the bytecode file extension is .class. Comments are used to document what a program is for and how a program is constructed. Comments help the programmers or users to communicate and understand the program. Comments are not programming statements and are ignored by the compiler. In Java, comments are preceded by two forward slashes (//) in a line or enclosed between /* and */ in multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees /*, it scans for the next */ and ignores any text between /* and */.15. System.out.println(...);JOptionPane.showMessageDialog(null,“Hello world”);Line 2. Main should be main.Line 2. static is missing.Line 3: Welcome to Java! should be enclosed inside double quotation marks.javac is the JDK command to compile a program program. java is the JDK command to run a program.18.19. Java interpreter cannot find the .class file. Make sure you placed the .class in the right place, and invoked java command with appropriate package name.The class does not have a main method, or the signature of the main method is incorrect.Thank you for evaluating AdreamSoft PDF to Word You can only convert 3 pages with the trial versionTo get all the pages converted, you need to purchase the software from/purchase/buy-pdf-to-word.html。
Java程序设计基础与实战-习题答案(人邮) 第2章作业参考答案
第2章作业参考答案1.填空题(1)表达式(2)强制类型转换(3)条件结构/分支结构(4)循环操作/循环体(5)顺序结构2.选择简答题(1)回答要点(2)回答要点布尔型和其它基本数据类型之间不能相互转换;byte 型能够转换为short、ini、、long> float 和double;short 可转换为int、long、float 和double;char 可转换为int、long> float 和double;int 可转换为long> float 和double;long 可转换为float 和double;float可转换为double(3)回答要点&表示当运算符两边的表达式的结果都为true时,整个运算结果才为true,否那么,只要有一方为false,那么结果为falseo &&具有短路的功能,即如果第一个表达式为false,那么不再计算第二个表达式。
(4)回答要点break应用在for、while和do…while循环语句中,用于强行退出循环,也就是忽略循环体中任何其他语句和循环条件的限制。
还可应用在switch语句中,用来终止switch语句。
continue语句是不可以应用在switch语句中的。
continue语句只能应用在for、while和do…while循环语句中,用于让程序直接跳过其后面的语句,进行下一次循环。
break语句和continue语句的区别在于,break语句将终止整个循环语句,而continue语句只结束本次循环。
4.编程题(1)源代码:参考本章资料文件夹下“作业1”。
(2)源代码:参考本章资料文件夹下“作业2”。
java语言程序设计课后习题答案
java语言程序设计课后习题答案Java语言程序设计课后习题答案Java语言是一种广泛应用于软件开发领域的编程语言,它具有简洁、可移植、面向对象等特点,因此在计算机科学与技术领域中得到了广泛的应用和推广。
学习Java语言程序设计是每个计算机科学与技术专业学生的必修课之一。
在学习过程中,老师通常会布置一些课后习题,以帮助学生巩固所学的知识。
本文将为大家提供一些Java语言程序设计课后习题的答案,希望对大家的学习有所帮助。
1. 编写一个Java程序,实现求阶乘的功能。
```javaimport java.util.Scanner;public class Factorial {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入一个正整数:");int n = scanner.nextInt();int result = 1;for (int i = 1; i <= n; i++) {result *= i;}System.out.println(n + "的阶乘为:" + result);}```2. 编写一个Java程序,实现判断一个数是否为素数的功能。
```javaimport java.util.Scanner;public class PrimeNumber {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入一个正整数:");int n = scanner.nextInt();boolean isPrime = true;for (int i = 2; i <= Math.sqrt(n); i++) {if (n % i == 0) {isPrime = false;break;}}if (isPrime) {System.out.println(n + "是素数");} else {System.out.println(n + "不是素数");}}```3. 编写一个Java程序,实现将一个字符串反转的功能。
《Java基础程序设计》_课后习题
第一章【思考题】1、简述path环境变量的作用。
2、请说说您对JVM的理解。
【答案】1、path环境变量就是系统环境变量中的一种,它用于保存一系列可执行文件的路径,每个路径之间以分号分隔。
当在命令行窗口运行一个可执行文件时,操作系统首先会在当前目录下查找就是否存在该文件,如果不存在会继续在path环境变量中定义的路径下去寻找这个文件,如果仍未找到,系统会报错。
2、JVM就是Java Virtual Machine的缩写,全称就是Java虚拟机。
Java语言的一个非常重要的特性就就是跨平台性,而Java虚拟机就是实现这一特性的关键。
不同的操作系统需要使用不同版本的虚拟机,这种方式使得Java语言能够“一次编写,到处运行”。
Java语言编译程序只需生成在Java虚拟机上运行的目标代码(字节码),就可以在多种平台上不加修改地运行。
Java虚拟机在执行字节码时,把字节码解释成具体平台上的机器指令执行。
第二章【思考题】1、请简述&与&&的区别。
2、简述break、continue与return语句的区别。
【答案】1、&与&&都可以用作逻辑与的运算符,表示逻辑与(and),当运算符两边的表达式的结果都为true时,整个运算结果才为true,否则,只要有一方为false,则结果为false。
当运算符“&”与“&&”的右边为表达式时,使用“&”进行运算,不论左边为true或者false,右边的表达式都会进行运算。
如果使用“&&”进行运算,当左边为false时,右边的表达式则不会进行运算,因此“&&”被称作短路与。
2、break语句:在switch条件语句与循环语句中都可以使用break语句。
当它出现在switch 条件语句中时,作用就是终止某个case并跳出switch结构。
当它出现在循环语句中,作用就是跳出循环语句,执行后面的代码。
Java程序设计案例教程 习题答案 第2章 Java编程基础
第2章Java编程基础一.填空题1. class2.单行注释、多行注释、文档注释3.基本数据、引用数据4.&、&&、|、||5.容器、06.47.强制8.129.小写二.判断1.错2.错3,对4.对5.对6.对7.对三.选择2.D 2.B3.C4. A5.C6.D7. A8. B9.A四.简答L Java语言的八种基本数据类型有:byte字节型,占一个字节。
short短整型,占两个字节。
血整型,占4个字节。
10ng长整型,占8个字节。
float单精度浮点型,占4个字节。
double双精度浮点型,占8个字节。
char字符型,占两个字节。
boolean型,表示逻辑值,有true和false两个值,分别占一个字节。
3.在switch条件语句和循环语句中都可以使用break语句。
当它出现在switch条件语句中时,作用是终止某个case并跳出switch结构。
当它出现在循环语句中,作用是跳出循环语句,执行循环后面的代码;continue语句用在循环语句中,它的作用是终止本次循环,执行下一次循环。
4.&和&&都可以用作逻辑与的运算符,表示逻辑与(and),当运算符两边的表达式的结果都为true时,整个运算结果才为true,否那么,只要有一方为false,那么结果为false。
当运算符和“&&”的右边为表达式时,使用进行运算,不管左边为true或者false,右边的表达式都会进行运算。
如果使用进行运算,当左边为false时,右边的表达式那么不会进行运算,因此“&&"被称作短路与。
五.编程2.参考答案public class Example28 { public static voidmain(String[] args) { int [] arr = { 22, 24, 76, 12, 21, 33 ); int min = getMin(arr);4.参考答案public class Exampl㊀05 {。
《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案《Java语言程序设计(基础篇)》(第10版梁勇著)第三章练习题答案3.1public class Exercise03_01 {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();double discriminant = b * b - 4 * a * c;if (discriminant < 0) {System.out.println("The equation has no real roots");}else if (discriminant == 0) {double r1 = -b / (2 * a);System.out.println("The equation has one root " + r1);}else { // (discriminant > 0)double r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);double r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);System.out.println("The equation has two roots " + r1 + " and " + r2);}}}3.1附加public class Exercise03_01Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter a numerator: ");int numerator = input.nextInt();System.out.print("Enter a denominator: ");int denominator = input.nextInt();if (numerator < denominator) {System.out.println(numerator + " / " + denominator + " is a proper fraction");}else if (numerator % denominator == 0) {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and it can be reduced to " + numerator / denominator);}else {System.out.print(numerator + " / " + denominator + " is an improper fraction ");System.out.println("and its mixed fraction is " + numerator / denominator + " + " +numerator % denominator + " / " + denominator);}}}3.2public class Exercise03_02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);int number1 = (int)(System.currentTimeMillis() % 10);int number2 = (int)(System.currentTimeMillis() * 7 % 10);int number3 = (int)(System.currentTimeMillis() * 3 % 10);System.out.print("What is " + number1 + " + " + number2 + " + " +number3 + "? ");int answer = input.nextInt();System.out.println(number1 + " + " + number2 + " + " + number3 +" = " + answer + " is " +(number1 + number2 + number3 == answer));}}3.2附加public class Exercise03_02Extra {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter the coordinates for two points: ");double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();double m = (y2 - y1) / (x2 - x1);double b = y1 - m * x1;System.out.print("The line equation for two points (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " + "y = ");if (m == -1)System.out.print("-x");else if (m == 1)System.out.print("x");elseSystem.out.print(m + "x");if (b > 0)System.out.println(" + " + b);else if (b < 0)System.out.println(" - " + (-1 * b));else// b is 0System.out.println();}}3.3public class Exercise03_03 {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();double detA = a * d - b * c;if (detA == 0) {System.out.println("The equation has no solution"); }else {double x = (e * d - b * f) / detA;double y = (a * f- e * c) / detA;System.out.println("x is " + x + " and y is " + y);}}}3.3附加public class Exercise03_03Extra {public static void main(String[] args) {final double RADIUS = 5;double angle = Math.random() * 2 * Math.PI;double x = RADIUS * Math.random() * Math.cos(angle);double y = RADIUS * Math.sin(angle);double distance = Math.pow(x * x + y * y, 0.5);System.out.println("The point is (" + x + ", " + y + ") and its distance to the center is " + distance);}}3.4public class Exercise03_04 {public static void main(String[] args) {int number = (int)(Math.random() * 12) + 1;// or int number = (int)(System.currentTimeMillis() % 12 + 1);// or int number = (int)(Math.random() * 12) + 1;if (number == 1)System.out.println("Month is Januaray");else if (number == 2)System.out.println("Month is Feburary");else if (number == 3)System.out.println("Month is March");else if (number == 4)System.out.println("Month is April");else if (number == 5)System.out.println("Month is May");else if (number == 6)System.out.println("Month is June");else if (number == 7)System.out.println("Month is July");else if (number == 8)System.out.println("Month is August");else if (number == 9)System.out.println("Month is September");else if (number == 10)System.out.println("Month is October");else if (number == 11)System.out.println("Month is November");else// if (number == 12)System.out.println("Month is December");}}3.5public class Exercise03_05 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter an integer for todaySystem.out.print("Enter today抯 day: ");int today = input.nextInt();System.out.print("Enter the number of days elapsed since today: ");int elapsedDays = input.nextInt();String nameForToday;if (today == 0)nameForToday = "Sunday";else if (today == 1)nameForToday = "Monday";else if (today == 2)nameForToday = "Tuesday";else if (today == 3)nameForToday = "Wednesday";else if (today == 4)nameForToday = "Thursday";else if (today == 5)nameForToday = "Friday";else// if (today == 6)nameForToday = "Saturday";int futureDay = (today + elapsedDays) % 7; String nameForFutureDay;if (futureDay == 0)nameForFutureDay = "Sunday";else if (futureDay == 1) nameForFutureDay = "Monday";else if (futureDay == 2) nameForFutureDay = "Tuesday";else if (futureDay == 3) nameForFutureDay = "Wednesday";else if (futureDay == 4) nameForFutureDay = "Thursday";else if (futureDay == 5) nameForFutureDay = "Friday";else// if (futureDay == 6) nameForFutureDay = "Saturday";System.out.println("Today is " + nameForToday+ " and the future day is " + nameForFutureDay); } }3.6public class Exercise03_06 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in pounds System.out.print("Enter weight in pounds: "); double weight = input.nextDouble();// Prompt the user to enter heightSystem.out.print("Enter feet: ");double feet = input.nextDouble();System.out.print("Enter inches: ");double inches = input.nextDouble();double height = feet * 12 + inches;// Compute BMIdouble bmi = weight * 0.45359237 / ((height * 0.0254) * (height * 0.0254));// Display resultSystem.out.println("BMI is " + bmi);if (bmi < 18.5)System.out.println("Underweight");else if (bmi < 25)System.out.println("Normal");else if (bmi < 30)System.out.println("Overweight");elseSystem.out.println("Obese");}}3.7/** Break down an amount into smaller units* Display the non-zero denominations only, and display singular* words for single units like 1 dollars, 1 penny, and display plural * words for more than one unit like 2 dollars, 3 pennies.*/public class Exercise03_07 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Receive the amount entered from the keyboardSystem.out.print("Enter an amount in double, for example 11.56: ");double amount = input.nextDouble();int remainingAmount = (int)(amount * 100);// Find the number of one dollarsint numberOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quarters in the remaining amountint numberOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numberOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numberOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numberOfPennies = remainingAmount;// Display resultsif (amount < 0) {System.out.println("Your amount is negative");System.exit(1);}else if (amount < 0) {System.out.println("Your amount is zero");System.exit(2);}System.out.println("Your amount " + amount + " consists of ");if (numberOfOneDollars > 1)System.out.println(numberOfOneDollars + "\ dollars");else if (numberOfOneDollars == 1)System.out.println(numberOfOneDollars + "\ dollar");if (numberOfQuarters > 1)System.out.println(numberOfQuarters + "\ quarters");else if (numberOfQuarters == 1)System.out.println(numberOfQuarters + "\ quarter");if (numberOfDimes > 1)System.out.println(numberOfDimes + "\ dimes");else if (numberOfDimes == 1)System.out.println(numberOfDimes + "\ dime");if (numberOfNickels > 1)System.out.println(numberOfNickels + "\ nickels");else if (numberOfNickels == 1)System.out.println(numberOfNickels + "\ nickel");if (numberOfPennies > 1)System.out.println(numberOfPennies + "\ pennies");else if (numberOfPennies == 1)System.out.println(numberOfPennies + "\ penny");}}3.8public class Exercise03_08 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three numbersSystem.out.print("Enter three integers: ");int number1 = input.nextInt();int number2 = input.nextInt();int number3 = input.nextInt();if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}if (number2 > number3) {int temp = number2;number2 = number3;number3 = temp;}if (number1 > number2) {int temp = number1;number1 = number2;number2 = temp;}System.out.println("The sorted numbers are "+ number1 + " " + number2 + " " + number3);}}public class Exercise03_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter an integerSystem.out.print("Enter the first 9 digits of an ISBN as integer: ");int number = input.nextInt();// Calculate checksum (You may write a loop to simplify it in Ch4int checksum =((number / 100000000 % 10) * 1 +(number / 10000000 % 10) * 2 +(number / 1000000 % 10) * 3 +(number / 100000 % 10) * 4 +(number / 10000 % 10) * 5 +(number / 1000 % 10) * 6 +(number / 100 % 10) * 7 +(number / 10 % 10) * 8 +(number % 10) * 9) % 11;System.out.print("The ISBN-10 number is ");// Display leading zeros, improve the solution using loops in the next chapterif (number / 100000000 == 0) {System.out.print("0");if (number / 10000000 == 0) {System.out.print("0");if (number / 1000000 == 0) {System.out.print("0");if (number / 100000 == 0) {System.out.print("0");if (number / 10000 == 0) { System.out.print("0");if (number / 1000 == 0) { System.out.print("0");if (number / 100 == 0) {System.out.print("0");if (number / 10 == 0) {System.out.print("0");if (number == 0) {System.out.print("0");}}}}}}}}}System.out.print(number);if (checksum == 10)System.out.print("X");elseSystem.out.print(checksum);}}3.10public class Exercise03_10 {public static void main(String[] args) {// 1. Generate two random single-digit integersint number1 = (int)(Math.random() * 10);int number2 = (int)(Math.random() * 10);// 2. Prompt the student to answer 搘hat is number1 + number2?? System.out.print("What is " + number1 + " + " + number2 + "? "); Scanner input = new Scanner(System.in);int answer = input.nextInt();// 4. Grade the answer and display the resultString replyString;if (number1 + number2 == answer)replyString = "You are correct!";elsereplyString = "Your answer is wrong.\" + number1 + " + "+ number2 + " should be " + (number1 + number2);System.out.println(replyString);}}3.11public class Exercise03_11 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter inputSystem.out.print("Enter a month in the year (e.g., 1 for Jan): ");int month = input.nextInt();System.out.print("Enter a year: ");int year = input.nextInt();int numberOfDaysInMonth = 0;switch (month) {case 1:System.out.print("January " + year);numberOfDaysInMonth = 31;break;case 2:System.out.print("February " + year);if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { numberOfDaysInMonth = 29;}else {numberOfDaysInMonth = 28;}break;case 3:System.out.print("March " + year);numberOfDaysInMonth = 31;break;case 4:System.out.print("April " + year);numberOfDaysInMonth = 30;break;case 5:System.out.print("May " + year);numberOfDaysInMonth = 31;break;case 6:System.out.print("June " + year);numberOfDaysInMonth = 30;break;case 7:System.out.print("July " + year);numberOfDaysInMonth = 31;break;case 8:System.out.print("August " + year);numberOfDaysInMonth = 31;break;case 9:System.out.print("September " + year);numberOfDaysInMonth = 30;break;case 10:System.out.print("October " + year);numberOfDaysInMonth = 31;break;case 11:System.out.print("November " + year);numberOfDaysInMonth = 30;break;case 12:System.out.print("December " + year);numberOfDaysInMonth = 31;break;}System.out.print(" has " + numberOfDaysInMonth + " days"); }}3.12public class Exercise03_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter a three-digit integer: ");int number = input.nextInt();if (number / 100 == number % 10)System.out.println(number + " is a palindrome");elseSystem.out.println(number + " is not a palindrome");}}3.13public class Exercise03_13 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Prompt the user to enter filing statusSystem.out.print("(0-single filer, 1-married jointly or qualifying widow(er),"+ "\2-married separately, 3-head of household)\" + "Enter the filing status: ");int status = input.nextInt();// Prompt the user to enter taxable incomeSystem.out.print("Enter the taxable income: ");double income = input.nextDouble();// Compute taxdouble tax = 0;if (status == 0) { // Compute tax for single filersif (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 82250) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950)* 0.25; } else if (income <= 171550) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (income - 82250) * 0.28;} else if (income <= 372950) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (income - 171550) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + (372950 - 171550) * 0.33 + (income - 372950) * 0.35;}} else if (status == 1) { // Compute tax for married file jointly if (income <= 16700) {tax = income * 0.10;} else if (income <= 67900) {tax = 16700 * 0.10 + (income - 16700) * 0.15;} else if (income <= 137050) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (income - 67900) * 0.25; } else if (income <= 208850) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (income - 137050) * 0.28;} else if (income <= 372950) {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (208850 - 137050) * 0.28 + (income - 208850) * 0.33;} else {tax = 16700 * 0.10 + (67900 - 16700) * 0.15 + (137050 - 67900) * 0.25 + (171950 - 137050) * 0.28 + (372950 - 208850) * 0.33+ (income - 372950) * 0.35;}} else if (status == 2) { // Compute tax for married separately if (income <= 8350) {tax = income * 0.10;} else if (income <= 33950) {tax = 8350 * 0.10 + (income - 8350) * 0.15;} else if (income <= 68525) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25; } else if (income <= 104425) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (income - 68525) * 0.28;} else if (income <= 186475) {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (income - 104425) * 0.33;} else {tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + (68525 - 33950) * 0.25 + (104425 - 68525) * 0.28 + (186475 - 104425) * 0.33 + (income - 186475) * 0.35;}} else if (status == 3) { // Compute tax for head of household if (income <= 11950) {tax = income * 0.10;} else if (income <= 45500) {tax = 11950 * 0.10 + (income - 11950) * 0.15;} else if (income <= 117450) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25; } else if (income <= 190200) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (income - 117450) * 0.28;} else if (income <= 372950) {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (income - 190200) * 0.33;} else {tax = 11950 * 0.10 + (45500 - 11950) * 0.15 + (117450 - 45500) * 0.25 + (190200 - 117450) * 0.28 + (372950 - 190200) * 0.33+ (income - 372950) * 0.35;}} else {System.out.println("Error: Wrong filing status");System.exit(1);}// Display the resultSystem.out.println("Tax is " + (int) (tax * 100) / 100.0);}}3.14public class Exercise03_14 {public static void main(String[] args) {// Obtain the random number 0 or 1int number = (int)(Math.random() * 2);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Guess head or tail? " +"Enter 0 for head and 1 for tail: ");int guess = input.nextInt();// Check the guessif (guess == number)System.out.println("Correct guess");else if (number == 0)System.out.println("Sorry, it is a head");elseSystem.out.println("Sorry, it is a tail");}}3.15public class Exercise03_15 {public static void main(String[] args) {// Generate a lotteryint lottery = (int)(Math.random() * 1000);// Prompt the user to enter a guessjava.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter your lottery pick (three digits): ");int guess = input.nextInt();// Get digitsint l1 = lottery / 100;int l2 = (lottery % 100) / 10; // l2 = (lottery / 10) % 10int l3 = lottery % 10;int g1 = guess / 100;int g2 = (guess % 100) / 10;int g3 = guess % 10;System.out.println("Lottery is " + lottery);// Check the guessif (guess == lottery)System.out.println("Exact match: you win $10,000");else if (g1 == l1 && g3 == l2 && g2 == l3 ||g2 == l1 && g1 == l2 && g3 == l3 ||g2 == l1 && g3 == l2 && g1 == l3 ||g3 == l1 && g1 == l2 && g2 == l3 ||g3 == l1 && g2 == l2 && g1 == l3)System.out.println("Match all digits: you win $3,000"); else if (g1 == l1 || g1 == l2 || g1 == l3 ||g2 == l1 || g2 == l2 || g2 == l3 ||g3 == l1 || g3 == l2 || g3 == l3)System.out.println("Match one digit: you win $1,000"); elseSystem.out.println("Sorry, no match");}}3.16public class Exercise03_16 {public static void main(String[] args) {double x = Math.random() * 100 - 50;double y = Math.random() * 200 - 100;System.out.println(x + ", " + y);}}3.17public class Exercise03_17 {public static void main(String[] args) {// Generate scissor, rock, paperint computerNumber = (int)(Math.random() * 3);// Prompt the user to enter scissor, rock, or paper java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("scissor (0), rock (1), paper (2): ");int userNumber = input.nextInt();// Check the guessswitch (computerNumber) {case 0:if (userNumber == 0)System.out.print("The computer is scissor. You are scissor too. It is a draw");else if (userNumber == 1)System.out.print("The computer is scissor. You are rock. You won");else if (userNumber == 2)System.out.print("The computer is scissor. You are paper. You lost");break;case 1:if (userNumber == 0)System.out.print("The computer is rock. You are scissor. You lost");else if (userNumber == 1)System.out.print("The computer is rock. You are rock too. It is a draw");else if (userNumber == 2)System.out.print("The computer is rock. You are paper. You won");break;case 2:if (userNumber == 0)System.out.print("The computer is paper. You are scissor. You won");else if (userNumber == 1)System.out.print("The computer is paper. You are rock. You lost");else if (userNumber == 2)System.out.print("The computer is paper. You are paper too.It is a draw");break;}}}3.18public class Exercise03_18 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter package weight: ");double w = input.nextDouble();if (w <= 1) {System.out.println("The shipping cost is $3.5");}else if (w <= 3) {System.out.println("The shipping cost is $5.5");}else if (w <= 10) {System.out.println("The shipping cost is $8.5");}else if (w <= 20) {System.out.println("The shipping cost is $10.5");}else {System.out.println("The package cannot be shipped");}}}3.19public class Exercise03_19 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in); // Enter three edgesSystem.out.print("Enter three edges (length in double): ");double edge1 = input.nextDouble();double edge2 = input.nextDouble();double edge3 = input.nextDouble();。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
}
// 第二章 P60 练习题 2.10 (科学:计算能量) import java.util.Scanner;
}
}
// 第二章 P59 练习题2.4 (将磅转换为千克) import java.util.Scanner;
public class PoundToKilogram {
public static void main(String[] args) { Scanner input = new Scanner(System.in);
System.out.println("The current time is " + hour + ":" + currentMinute + ":" + currentSecond);
}
}
// 第二章 P60 练习题 2.9 (物理:加速度) import java.util.Scanner;
public class Acceleration {
System.out.println("The gratuity is $" + choujin + " and total is $" + zongfeiyong);
}
}
// 第二章 P60 练习题2.6 (求一个整数各位数的和) import java.util.Scanner;
public class QiuHe {
public class TheNumberOfYears {
public static void main(String[] args) { Scanner input = new Scanner(System.in);
System.out.print("Enter the number of minutes: "); long minutes = input.nextLong();
}
}
// 第二章 P60 练习题2.5 (财务应用程序:计算小费) import java.util.Scanner;
public class ChoujinHeZongqianshu {
public static void main(String[] args) { Scanner input = new Scanner(System.in);
System.out.print("Enter a number in pounds: "); double pound = input.nextDouble(); double kilogram = pound * 0.454;
System.out.println(pound + " pounds is " + kilogram + " kilograms");
System.out.print("Enter the time zone offset to GMT: "); long timeZoneOffset = input.nextLong(); // 此处用long还是int?
long totalMilliseconds = System.currentTimeMillis(); long totalSeconds = totalMilliseconds / 1000; long currentSecond = totalSeconds % 60; long totalMinutes = totalSeconds / 60; long currentMinute = totalMinutes % 60; long totalHours = totalMinutes / 60; long currentHour = totalHours % 24; long hour = currentHour + timeZoneOffset;
System.out.print("Enter the radius and length of a cylinder: "); double radius = input.nextDouble(); double length = input.nextDouble();
// 圆柱体面积=半径×半径×PI,圆柱体体积=面积×高 final double PI = 3.14159; double area = radius * radius *PI; double volume = area * length; System.out.println("The area is " + area); System.out.println("The volume is " + volume);
public class ComputeEnergy {
public static void main(String[] args) { Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of water in kilograms: "); double amountOfWater = input.nextDouble(); System.out.print("Enter the initial temperature: "); double initialTem = input.nextDouble(); System.out.print("Enter the final temperature: "); double finalTem = input.nextDouble();
}
}
// 第二章 P59 练习题2.2 (计算圆柱体的体积) import java.util.Scanner;
public class VolumeOfCylinder {
public static void main(String[] args) { Scanner input = new Scanner(System.in);
int num2 = (int)(num1 / 100) + (int)(num1 / 10 % 10) + (int)(num1 % 10); System.out.println("The sum of the digits is " + num2);
}
}
// 第二章 P60 练习题2.7 (求出年数) import java.util.Scanner;
System.out.print("Enter the subtotal and gratuity rate: "); double feiyong = input.nextDouble(); double choujinlv = input.nextDouble(); double choujin = feiyong * (choujinlv / 100); double zongfeiyong = feiyong + choujin;
System.out.print("Enter a value for feet: "); double feet = input.nextDouble(); double meter = feet * 0.305;
System.out.println(feet + " feet is " + meter + " meters");
《Java语言程序设计(基础篇)》(第10版 梁勇 著) 第二章 基本程序设计 练习题答案
本人在自学编程过程中,发现本书答案很难找,找到的要么不完整、要么错误百出,所以我将自己所做的 练习题答案,提供给有需要者,供大家交流。本章答案均为本人一字一字所敲,答案均经过验证,虽为初学者, 但代码均按照书中规范要求书写,如有错误或更好的建议,请指正交流。
// 计算一年的总秒数 double totalSeconds,chusheng,siwang,qianru; totalSeconds = 365 * 24 * 60 * 60; // 分别计算一年中出生、死亡和移民迁入人口数 chusheng = totalSeconds / 7.0; siwang = totalSeconds / 13.0; qianru = totalSeconds / 45.0;
int years = (int)((minutes / 60 / 24) / 365); int days = (int)((minutes / rintln(minutes + " minutes is approximately " + years +
public static void main(String[] args) { Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 0 and 1000: "); int num1 = input.nextInt();
public static void main(String[] args) { Scanner input = new Scanner(System.in);