java第二章练习题答案

合集下载

Java入门经典第2章动手写Hello World知识点练习答案及课后习题答案

Java入门经典第2章动手写Hello World知识点练习答案及课后习题答案

第2章 动手写“Hello World”并不是每台计算机都可以运行Java程序,要运行Java程序,计算机必须搭建Java开发环境,而编写Java程序则可以使用任何的文本编辑工具,如最简单的文本编辑工具之一——记事本。

搭建Java开发环境是每一位Java程序员必须掌握并熟练使用的一项技能。

本章为大家介绍接触Java的第一步——搭建Java开发环境。

知识点:1、并不是每台计算机都可以运行Java程序,要运行Java程序,计算机必须搭建Java开发环境,而编写Java程序则可以使用任何的文本编辑工具,如最简单的文本编辑工具之一——记事本。

练习:1、并不是每台计算机都可以运行Java程序,要运行Java程序,计算机必须搭建 ,而编写Java程序则可以使用任何的 ,如最简单的文本编辑工具之一—— 。

通过本章的学习,希望读者可以达到以下的学习目的:□ 学会下载JDK。

□ 掌握如何安装JDK。

□ 掌握如何在Windows系统下配置和测试JDK。

□ 学会使用记事本编写Java程序。

□ 学会编译和运行Java程序。

2.1 搭建Java开发环境所谓“工欲善其事,必先利其器”,在学习一门语言之前,首先需要把整个开发环境搭建好。

要编译和执行Java程序,JDK是必备的。

下面将具体介绍下载并安装JDK及配置环境变量的方法。

2.1.2 下载JDK由于Sun公司已经被Oracle收购,因此JDK可以在Oracle公司的官方网站(/index.html)下载。

下面以目前最新版本JDK 7 Update 3为例介绍下载JDK的方法,具体下载步骤如下。

Step(1)打开IE浏览器,在地址栏中输入Oracle公司网站地址“/index.html”,并按下<Enter>键,进入到图2.1所示的Oracle官方网站主页面。

单击Oracle主页中的“Downloads”选项卡,然后在“Popular Downloads”栏目中单击“Java for Developers”超链接,这样就进入到Java SE相关资源下载页面。

Java语言程序设计(第三版)第二章课后习题答案(仅供参考)

Java语言程序设计(第三版)第二章课后习题答案(仅供参考)

Java语⾔程序设计(第三版)第⼆章课后习题答案(仅供参考)2.1 注意不同类型转换1import java.util.Scanner;23public class Ch02 {4public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6double f = sc.nextDouble();7double t = (5.0/9)*(f-32); // 注意 (5/9) 结果为整形要写成 (5.0/9)8 System.out.println(t)9 }2.21import java.util.Scanner;23public class Ch02 {4public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.println("请输⼊圆柱体半径和⾼:");7double r = sc.nextDouble();8double h = sc.nextDouble();9double v = Math.PI * r * r * h; //圆周率⽅法 Math.PI10 System.out.println(v);11 }2.31import java.util.Scanner;23public class Ch02 {4public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.println("请输⼊体重和⾝⾼:");7double g = sc.nextDouble();8double h = sc.nextDouble();9double BMI = g / (h * h);10 System.out.println(BMI);11 }2.4 使⽤循环每次对个位取数相加取数后除以10 使前⼀位变为个位继续判断⼩于等于0时停⽌1import java.util.Scanner;23public class Ch02 {4public static void main(String[] args) {5int sum = 0;6 Scanner sc = new Scanner(System.in);7int num1 = sc.nextInt();8while (num1 > 0) // 与 0 ⽐较判断是否需要取数9 {10 sum += (num1%10); // 通过取余获得个位数字11 num1 /= 10; // 每次取余后除以1012 }13 System.out.println(sum);14 }2.5 注意 System.currentTimeMillis()⽅法返回long形需要转换为int形1public class Ch02 {2public static void main(String[] args) {3// 通过 System.currentTimeMillis() ⽅法获得从1970年1⽉1⽇ 00:00:00 到现在的毫秒数4// 28800000 是格林时间与我们时区的时间差值5// 对 86400000 取余是把满⼀天的时间都去掉获取多出来的不⾜⼀天的时间6int t = (int)((System.currentTimeMillis()+28800000)%86400000);7int hour = t/3600000; // 除 3600000 获取满⼩时的个数即求⼩时为⼏点8int mine = t%3600000/60000; // 计算不⾜⼀⼩时的时间⾥有多少分钟9int s = t%3600000%60000/1000; // 计算不⾜⼀分钟的时间⾥有多少秒不要忘记除以 1000 (因为单位为毫秒)10 System.out.println("当前时间: "+hour+":"+mine+":"+s+" GMT");11 }2.6 a 不能为 0 b2 - 4 * a * c 不能为 01import java.util.Scanner;23public class Ch02 {4public static void main(String[] args) {5double sum,a,b,c,t;6 Scanner sc = new Scanner(System.in);7while (true) {8 a = sc.nextDouble();9 b = sc.nextDouble();10 c = sc.nextDouble();11 t = b*b-4*a*c;12if (a == 0) {13 System.out.println("a 不能为 0,请重新测试 ^_^");14 } else if (t < 0) {15 System.out.println("b*b-4*a*c不能为0,请重新测试");16 }17else18 {19break;20 }21 }22 sum = ((-b+Math.sqrt(t)/(2*a))); //( 2*a ) 注意加括号23 System.out.println(sum);2.7 注意计算公式先后顺序多使⽤⼩括号1import java.util.Scanner;23public class Ch02 {4public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6double yrate = sc.nextDouble();7double amount = sc.nextDouble();8double year = sc.nextDouble();9double month = (amount * (yrate/12))/(1-(1/Math.pow(1+yrate/12,year*12)));10double sumamount = month*12*year;11 System.out.println("⽉⽀付⾦额:"+month+"\n总偿还⾦额:"+sumamount);12 }。

JAVA期末复习题及答案——第二章

JAVA期末复习题及答案——第二章

JAVA期末复习题及答案——第二章一、选择题1.以下关于Java标识符的叙述中,错误的是:BA、Java标识符的后续字符可以是字母,下划线,美元符号和数字B、Java标识符是不区分大小写的C、Java标识符没有最大长度的限制D、Java的标识符不可以用Java关键字来定义2.以下哪个标识符为合法标识符:AA、aVariable1B、1varC、var%D、static3.以下哪个标识符为非法的:CA、$var2B、_var2C、var2#D、var2$4.以下哪个不是Java中的整数类型:CA、byteB、intC、LongD、short5.请阅读下面程序import java.io.*;public class TypeTransition{public static void main(String args[]){char a=’a’;int i=100;long y=456L;int aa=a+i;long yy=y-aa;System.out.print(“aa=”+aa);System.out.print(“yy=”+yy);则程序的执行结果为:AA、aa=197 yy=259B、aa=177 yy=259C、aa=543 yy=288D、aa=197 yy=3336.阅读下面程序import java.io.*;public class TypeTransition{public static void main(String args[]){char a=’h’;int i=100;int j=97;int aa=a+i;System.out.println(“aa=”+aa);char bb=(char)j;System.out.println(“bb=”+bb);}}如果输出结果的第二行为bb=a,那么第一行的输出是:B A、aa=1 B、aa=204 C、aa=v D、aa=1567.阅读下面程序public class Increment{public static void main(String args[]){int c;c=5;System.out.println(c);System.out.println(c++);System.out.println(c);}}程序的运行结果是:BA、5B、5C、6D、66 57 6 6 6 7 68.下列标识符(名字)命名原则中,正确的是:DA、类名的首字母小写B、变量和方法名的首字母大写C、接口名的首字母小写D、常量完全大写10.阅读下列代码public class Test2005{public static void main(String args[]){System.out.println(~(0xa5)&0xaa);}}其运行结果是:BA、0xa5B、10C、0x50D、0xaa11.阅读下列代码public class Test2005{public static void main(String args[]){System.out.println((3>2)?4:5);}}其运行结果为:CA、2B、3C、4D、512.阅读下列代码public class Test{public static void main(String args[]){System.out.println(89>>1);}}其运行结果为:AA、44B、45C、88D、8913.下列叙述中,正确的是:AA、声明变量时必须指定一个类型B、Java认为变量number与Number相同C、Java中唯一的注释方式是”//”D、源文件中public类可以有0个或多个14.下列属于合法的Java标识符的是:DA、”ABC”B、&5678C、+rriwoD、saler15.下列代表十六进制整数的是:DA、0123B、1900C、fa00D、0xa216.++运算操作数的个数是:AA、1个B、2个C、3个D、4个17.在switch(expression)语句中,expression的数据类型不能是:A A、double B、char C、byte D、short18.下列代码中,将引起编译错误的行是:B1) public class Excecise{2) public static void main(String args[]){3) float f=0.0;4) f+=1.0;5) }6) }A、第2行B、第3行C、第4行D、第6行19.以下叙述错误的是( A )。

JAVA第二章 课后习题答案

JAVA第二章 课后习题答案

9.
编写程序,将十进制整数转换为二进制。 public class Tentotwo { public static void main(String[] args) { int a = 123; int remainder; int sum = 0; int k = 1; while(a != 0){ remainder = a %2; a /= 2; sum = sum + remainder * k; k *= 10; } //对目标数字求余 //对目标数字求商 //求和 //改变位数 //定义一个变量并赋给他一个十进制的值 //定义一个变量用于存储余数 //定义一个变量用于存放和 //定义一个变量控制位数
4
Hale Waihona Puke } }7.编写程序,求 100~999 之间所有的三位水仙花数。 (水仙花数是指一个 n 位数 ( n≥3 ),它的 每个位上的数字的 n 次幂之和等于它本身,例如:1^3 + 5^3+ 3^3 = 153) public class Shuixian { public static void main(String[] args) { int b1, b2, b3; for(int m=101; m<1000; m++) { b3=m/100; b2=m%100/10; b1=m%10; if ((b3*b3*b3+b2*b2*b2+b1*b1*b1)==m) System.out.println(m+"是一个水仙花数"); } } }
6
System.out.println("10 进制的 123 转换为 2 进制结果为:" + sum ); } }

JAVA_WEB第二章习题

JAVA_WEB第二章习题
数据不是URL的一部分而是作为请求的消息体发送,在浏览器的地址栏中对用户是不可见的
数据缓存
数据在浏览器的URL历史中缓存
数据不能在浏览器的URL历史中缓存
8.(C)
9.(1)RequestDispatcher对象是请求转发器,他用来把当前请求转发到指定的资源;
(2)响应重定向实际上是服务器向浏览器发送一个特殊的响应头(Location 状态码302),他告诉浏览器连接到新的位置。使用这种方式可以在浏览器的地址栏看到地址的变化。重定向是作为一个新的请求来看待的,因此,所有的请求作用域的参数在重定向到下一个页面都会失效。另外,使用sendRedirect()重定向时,资源不能位于WEB-INF目录中。
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import com.demo.Studrvlet", urlPatterns = { "/input.do" })
out.println("<center>");
out.println("学号:" + stud.getSno() + "<br>");
out.println("姓名:" + stud.getName() + "<br>");
out.println("<a href=\"/helloapp/input.html\">返回输入页面</a>");

Java语言程序设计 课后习题+答案

Java语言程序设计 课后习题+答案

第一章课后习题1.编译Java程序的命令是什么2.执行Java程序的命令是什么应用程序和小程序的区别是什么4.编写一个application ,实现在屏幕上打印自己名字的功能。

第一章课后习题答案1.编译Java程序的命令是什么答案:javac 源文件名2.执行Java程序的命令是什么java 主类名应用程序和小程序的区别是什么Java application由Java解释器独立运行字节码由专门的命令行启动程序执行程序中有定义了main()方法的主类Java applet不能独立运行,字节码必须嵌入HTML文档当浏览器调用含applet的Web页面时执行程序中含有java. applet. Applet 类的子类4.编写一个application ,实现在屏幕上打印自己名字的功能。

class Test{public static void main(String[] args){张三”);}}第二章课后习题(1)一、选择题1.下列变量定义错误的是。

A) int a; B) double b=; C) boolean b=true; D)float f=;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)56是一种_____________A) 数据类型 B)java包 C)字符编码 D)java类+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)语言中,占用32位存储空间的是__________。

java程序设计课后第二章习题程序答案

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语言程序设计(基础篇)》(第10版 梁勇 著)第二章练习题答案

《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二章练习题答案

《Java语言程序设计(基础篇)》(第10版梁勇著)第二章练习题答案2.1public class Exercise02_01 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter a temperature in CelsiusSystem.out.print("Enter a temperature in Celsius: ");double celsius = input.nextDouble();// Convert it to Fahrenheitdouble fahrenheit = (9.0 / 5) * celsius + 32;// Display the resultSystem.out.println(celsius + " Celsius is " +fahrenheit + " Fahrenheit");}}2.1附加public class Exercise02_01Extra {// Main methodpublic 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();System.out.println("The slope for the line that connects two points (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " +(y2 - y1) / (x2 - x1));}}2.2public class Exercise02_02 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter radius of the cylinderSystem.out.print("Enter the radius and length of a cylinder: ");double radius = input.nextDouble();double length = input.nextDouble();double area = radius * radius * 3.14159;double volume = area * length;System.out.println("The area is " + area);System.out.println("The volume of the cylinder is " + volume);}}2.2附加public class Exercise02_02Extra {public static void main(String[] args) {System.out.print("Enter the ball travel time in seconds: ");Scanner input = new Scanner(System.in);double t = input.nextDouble();final double g = 9.8;double d = g * t * t / 2;System.out.print("The height of the building is " + d + " meters "); }}2.3public class Exercise02_03 {public static void main(String[] args) {// Enter footjava.util.Scanner input = new java.util.Scanner(System.in);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");}}2.3附加public class Exercise02_03Extra {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter the friction force in Newtons: ");double f = input.nextDouble();System.out.print("Enter the object抯 mass in kg: ");double m = input.nextDouble();System.out.print("Enter the object抯 acceleration in m/s^2: ");double a = input.nextDouble();final double g = 9.8;double u = (f - m * a) / (m * g);System.out.print("The coefficient for friction is " + u);}}2.4public class Exercise02_04 {public static void main(String[] args) {// Prompt the inputjava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter a number in pounds: ");double pounds = input.nextDouble();double kilograms = pounds * 0.454;System.out.println(pounds + " pounds is " + kilograms + " kilograms"); }2.5public class Exercise02_05 {public static void main(String args[]) {// Read subtotaljava.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter subtotal and gratuity rate: ");double subtotal = input.nextDouble();double rate = input.nextDouble();double gratuity = subtotal * rate / 100;double total = subtotal + gratuity;System.out.println("The gratuity is " + gratuity +" total is " + total);}}2.6// Exercise02_06.java: Summarize all digits in an integer < 1000 public class Exercise02_06 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Read a numberSystem.out.print("Enter an integer between 0 and 1000: ");int number = input.nextInt();// Find all digits in numberint lastDigit = number % 10;int remainingNumber = number / 10;int secondLastDigit = remainingNumber % 10;remainingNumber = remainingNumber / 10;int thirdLastDigit = remainingNumber % 10;// Obtain the sum of all digitsint sum = lastDigit + secondLastDigit + thirdLastDigit;// Display resultsSystem.out.println("The sum of all digits in " + number+ " is " + sum);}}2.7public class Exercise02_07 {public static void main(String[] args) {// Prompt the user to enter the number of minutesScanner input = new Scanner(System.in);System.out.print("Enter the number of minutes: ");long minutes = input.nextLong();long numberOfDays = minutes / (24 * 60);long numberOfYears = numberOfDays / 365;// Display resultsSystem.out.println(minutes + " minutes is approximately " +numberOfYears + " years and " + (numberOfDays % 365) + " days"); }2.8public class Exercise02_08 {public static void main(String[] args) {// Prompt the user to enter the time zone offset to GMTScanner input = new Scanner(System.in);System.out.print("Enter the time zone offset to GMT: ");long timeZoneOffset = input.nextInt();// Obtain the total milliseconds since the midnight, Jan 1, 1970long totalMilliseconds = System.currentTimeMillis();// Obtain the total seconds since the midnight, Jan 1, 1970long totalSeconds = totalMilliseconds / 1000;// Compute the current second in the minute in the hourlong currentSecond = totalSeconds % 60;// Obtain the total minuteslong totalMinutes = totalSeconds / 60;// Compute the current minute in the hourlong currentMinute = totalMinutes % 60;// Obtain the total hourslong totalHours = totalMinutes / 60;// Compute the current hourlong currentHour = (totalHours + timeZoneOffset) % 24;// Display resultsSystem.out.println("Current time is " + currentHour + ":"+ currentMinute + ":" + currentSecond);}}2.9public class Exercise02_09 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter v0, v1, and t: ");double v0 = input.nextDouble();double v1 = input.nextDouble();double t = input.nextDouble();double a = (v1 - v0) / t;System.out.println("The average acceleration is " + a);}}2.10public class Exercise02_10 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);System.out.print("Enter the amount of water in kilograms: ");double mass = input.nextDouble();System.out.print("Enter the initial temperature: ");double initialTemperature = input.nextDouble();System.out.print("Enter the final temperature: ");double finalTemperature = input.nextDouble();double energy =mass * (finalTemperature - initialTemperature) * 4184;System.out.print("The energy needed is " + energy);}}2.11public class Exercise02_11 {public static void main(String[] args) {// Prompt the user to enter the time zone offset to GMTScanner input = new Scanner(System.in);System.out.print("Enter the number of years: ");int numberOfYears = input.nextInt();double population = 312032486 + numberOfYears * 365 * 24 * 60 * 60 / 7.0 -numberOfYears * 365 * 24 * 60 * 60 / 13.0 + numberOfYears * 365 * 24 * 60 * 60 / 45.0;// Display resultsSystem.out.println("The population in " + numberOfYears + " years is " + (int)population);}}2.12public class Exercise02_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter speed v: ");double v = input.nextDouble();System.out.print("Enter acceleration a: ");double a = input.nextDouble();double length = v * v / (2 * a);System.out.println("The minimum runway length for this airplane is " + length + " meters");}}2.13public class Exercise02_13 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter monthly saving amount: ");double monthlyDeposit = input.nextDouble();double currentValue = monthlyDeposit;// First month valuecurrentValue = currentValue * (1 + 0.00417);System.out.println("After the first month, the account value is " +currentValue);// Second month valuecurrentValue = (currentValue + monthlyDeposit) * (1 + 0.05 / 12);System.out.println("After the second month, the account value is " + currentValue);// Third month valuecurrentValue = (currentValue + monthlyDeposit) * (1 + 0.05 / 12);System.out.println("After the third month, the account value is " + currentValue);// Fourth month valuecurrentValue = (currentValue + monthlyDeposit) * (1 + 0.05 / 12);// Fifth month valuecurrentValue = (currentValue + monthlyDeposit) * (1 + 0.05 / 12);// Sixth month valuecurrentValue = (currentValue + monthlyDeposit) * (1 + 0.05 / 12);System.out.println("After the sixth month, the account value is " + currentValue);}}2.14public class Exercise02_14 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Prompt the user to enter weight in poundsSystem.out.print("Enter weight in pounds: ");double weight = input.nextDouble();// Prompt the user to enter height in inchesSystem.out.print("Enter height in inches: ");double height = input.nextDouble();double bmi = weight * 0.45359237 / (height * 0.0254 * height * 0.0254);System.out.print("BMI is " + bmi);}2.15public class Exercise02_15 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter the first point with two double valuesSystem.out.print("Enter x1 and y1: ");double x1 = input.nextDouble();double y1 = input.nextDouble();// Enter the second point with two double valuesSystem.out.print("Enter x2 and y2: ");double x2 = input.nextDouble();double y2 = input.nextDouble();// Compute the distancedouble distance = Math.pow((x1 - x2) * (x1 - x2) +(y1 - y2) * (y1 - y2), 0.5);System.out.println("The distance of the two points is " + distance);}}2.16public class Exercise02_16 {public static void main(String[] args) {Scanner input = new Scanner(System.in);// Enter the side of the hexagonSystem.out.print("Enter the side: ");double side = input.nextDouble();// Compute the areadouble area = 3 * 1.732 * side * side / 2;System.out.println("The area of the hexagon is " + area); }}public class Exercise02_17 {// Main methodpublic static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter the temperature in FahrenheitSystem.out.print("Enter the temperature in Fahrenheit between -58 and 41: ");double fahrenheit = input.nextDouble();// Enter the wind speed miles per hourSystem.out.print("Enter the wind speed miles per hour " +"(must be greater than or equal to 2) : ");double speed = input.nextDouble();// Compute wind chill indexdouble windChillIndex = 35.74 + 0.6215 * fahrenheit - 35.75 *Math.pow(speed, 0.16) + 0.4275 * fahrenheit *Math.pow(speed, 0.16);// Display the resultSystem.out.println("The wind chill index is " + windChillIndex);}}2.18public class Exercise02_18 {// Main methodpublic static void main(String[] args) {System.out.println("a b pow(a, b)");System.out.println("1 2 " + (int)Math.pow(1, 2));System.out.println("2 3 " + (int)Math.pow(2, 3));System.out.println("3 4 " + (int)Math.pow(3, 4));System.out.println("4 5 " + (int)Math.pow(4, 5));System.out.println("5 6 " + (int)Math.pow(5, 6));}}2.19public class Exercise02_19 {public static void main(String[] args) {// Enter three points for a triangleSystem.out.print("Enter three points for a triangle: ");Scanner input = new Scanner(System.in);double x1 = input.nextDouble();double y1 = input.nextDouble();double x2 = input.nextDouble();double y2 = input.nextDouble();double x3 = input.nextDouble();double y3 = input.nextDouble();// Compute the length of the three sidesdouble side1 = Math.pow((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2), 0.5);double side2 = Math.pow((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3), 0.5);double side3 = Math.pow((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2), 0.5);double s = (side1 + side2 + side3) / 2;double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);System.out.println("The area of the triangle is " + area);}}2.20public class Exercise02_20 {public static void main(String args[]) {Scanner input = new Scanner(System.in);// Obtain inputSystem.out.print("Enter balance and annual interest rate: ");double balance = input.nextDouble();double annualInterestRate = input.nextDouble();double monthlyInterestRate = annualInterestRate / 1200;double interest = balance * monthlyInterestRate;// Display outputSystem.out.println("The interest is " + (int)(100* interest) / 100.0); }}2.21// Exercise02_11.java: Create a method for computing future valuepublic class Exercise02_21 {public static void main(String[] args) {java.util.Scanner input = new java.util.Scanner(System.in);// Enter the investment amountSystem.out.print("Enter the investment amount, for example 120000.95: ");double investmentAmount = input.nextDouble();// Enter yearly interest rateSystem.out.print("Enter annual interest rate, for example 8.25: ");double annualInterestRate = input.nextDouble();// Obtain monthly interest ratedouble monthlyInterestRate = annualInterestRate / 1200;// Enter number of yearsSystem.out.print("Enter number of years as an integer, for example 5: ");int numOfYears = input.nextInt();double futureValue =investmentAmount * Math.pow(1 + monthlyInterestRate,numOfYears * 12);System.out.print("Future value is " +(int)(futureValue * 100) / 100.0);}}2.22public class Exercise02_22 {// 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 integer, for example 1156 \nfor 11 dollars and 56 cents: ");int amount = input.nextInt();int remainingAmount = amount;// Find the number of one dollarsint numOfOneDollars = remainingAmount / 100;remainingAmount = remainingAmount % 100;// Find the number of quaters in the remaining amountint numOfQuarters = remainingAmount / 25;remainingAmount = remainingAmount % 25;// Find the number of dimes in the remaining amountint numOfDimes = remainingAmount / 10;remainingAmount = remainingAmount % 10;// Find the number of nickels in the remaining amountint numOfNickels = remainingAmount / 5;remainingAmount = remainingAmount % 5;// Find the number of pennies in the remaining amountint numOfPennies = remainingAmount;// Display resultsSystem.out.println("Your amount " + amount + " consists of "); System.out.println(numOfOneDollars + " dollars");System.out.println(numOfQuarters + " quarters");System.out.println(numOfDimes + " dimes");System.out.println(numOfNickels + " nickels");System.out.println(numOfPennies + " pennies");}}2.23public class Exercise02_23 {public static void main(String args[]) {Scanner input = new Scanner(System.in);System.out.print("Enter the driving distance: ");double distance = input.nextDouble();System.out.print("Enter miles per gallon: ");double milesPerGallon = input.nextDouble();System.out.print("Enter price per gallon: ");double pricePerGallon = input.nextDouble();System.out.println("The cost of driving is $" + (distance / milesPerGallon) * pricePerGallon); }}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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循环实现重复执行某段代码。

示例代码如下:
for (int i = 0; i < 5; i++) {
System.out.println("Hello World");
}
8. 问题:如何使用while循环实现条件循环?
答案:可以使用while循环实现条件循环。

示例代码如下:
int num = 0;
while (num < 5) {
System.out.println("Hello World");
num++;
}
9. 问题:如何使用switch语句实现多分支选择?
答案:可以使用switch语句实现多分支选择。

示例代码如下: int num = 1;
switch (num) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
default:
System.out.println("其他");
break;
}
10. 问题:如何使用数组存储多个相同类型的数据?
答案:可以使用数组存储多个相同类型的数据。

示例代码如下:
int[] nums = {1, 2, 3, 4, 5};
通过以上答案,我们对Java第二章练习题有了更深入的理解。

掌握这些基本概念和语法,对于后续的学习和实践将起到重要的作用。

希望大家能够通过不断的练习和实践,提升自己的编程能力。

相关文档
最新文档