Java语言程序设计 习题
第四章
4.2习题
计算下面的方法调用:
double a = Math.sqrt(4);
double b = Math.sin(2 * Math.PI);
double c = Math.cos(2 * Math.PI);
double d = Math.pow(2, 2);
double e = Math.log(Math.E);
double f = Math.exp(1);
double g = Math.max(2, Math.min(3, 4));
double h = Math.rint(-2.5);
double i = Math.ceil(-2.5);
double j = Math.floor(-2.5);
double k = Math.round(-2.5f);
double l = Math.round(-2.5);
double m = Math.rint(2.5);
double n = Math.ceil(2.5);
double o = Math.floor(2.5);
double p = Math.round(2.5f);
double q = Math.round(2.5);
double r = Math.round(Math.abs(-2.5));
a = 2.0
b = -2.4492935982947064E-16
c = 1.0
d = 4.0
e = 1.0
f = 2.718281828459045
g = 3.0
h = -2.0
i = -2.0
j = -3.0
k = -2.0
l = -2.0
m = 2.0
n = 3.0
o = 2.0
p = 3.0
q = 3.0
r = 3.0
下述说法是否正确? 三角函数方法中的参数是以弧度为单位的角
正确
编写一条语句,将47°转换为弧度值,并将结果赋给一个变量
double x = Math.toRadians(47);
System.out.print(x);
编写一条语句.将 π \pi π / 7转换为角度值,并将结果賦给一个变量
double x = Math.toDegrees(Math.PI / 7);
System.out.print(x);
编写一个表达式,返回34-55的一个随机整数
int x = (int)(Math.random() * 22 + 34);
编写一个表达式,返回0-999的一个随机整数
int x = (int)(Math.random() * 1000);
编写一个表达式,返回5.5 - 55.5的一个随机数
double x = Math.random() * 501 + 55) / 10
//该表达式不准确,有小概率会超出范围
为什么Math类不需要导人?
Math类在java.lang包中,lang包都是隐式导入的
Math.log(Math.exp(5.5))等于多少?
5.5
Math.exp(Math.log(5.5))等于多少?
5.5
Math.asin(Math.sin(Math.PI / 6))等于多少?
0.5235987755982988
Math.sin(Math.asin(Math.PI / 6))等于多少?
0.5235987755982988
4.3 习题
使用输出语句,得到’1’、‘A’、‘B’、‘a’、'b’的ASCII码。
public class Main {
public static void main(String[] args) {
int a ='1';
System.out.println(a);
int b ='A';
System.out.println(b);
int c ='a';
System.out.println(c);
int d ='B';
System.out.println(d);
int e ='b';
System.out.println(e);
}
}
49
65
97
66
98
使用输出语句得到十进制码40、59、79、85和90的字符。
System.out.println((char)40 + " " + (char)59 + " " + (char)79 + " " + (char)85 + " " + (char)90);
( ; O U Z
使用输出语句得到十六进制码40、5A、71、72和7A的字符。
System.out.println((char) 0x40 + " " + (char) 0x5A + " " + (char) 0x71 + " " + (char) 0x72 + " " + (char) 0x7A);
以下哪些是正确的字符直接值? ‘1’, ‘\u345dE’, ‘\u3fFa’, ‘\b’, ‘\t’
//除了第二个,全都是
int b = '\t';
System.out.print(b);
如何显示字符\和’’
System.out.print("\\");
System.out.print("\"");
求以下值
int i = '1';
int j = '1' + '2' * ('4' - '3') + 'b' / 'a';
int k = 'a';
char c = 90;
System.out.print(i + "\n" + j + "\n" + k + "\n" + c);
49
100
97
Z
下面涉及类型转换的转换合法吗? 如果合法,给出转换后的结果
public class Main {
public static void main(String[] args) {
char c = 'A';
int i = (int)c;
System.out.println(c + "\t" + i);
float f = 1000.34f;
int x = (int)f;
System.out.println(f + "\t" + x);
double d = 1000.34;
int y = (int)d;
System.out.println(d + "\t" + y);
int z = 97;
char zz = (char)i;
System.out.println(z + "\t" + zz);
}
}
A 65
1000.34 1000
1000.34 1000
97 A
给出下面程序的输出结果
public class Main {
public static void main(String[] args) {
char x = 'a';
char y = 'c';
System.out.println(++x);
System.out.println(y++);
System.out.println(x - y);
}
}
b
c
-2
编写代码,产生随机的小写字母。
public class Main {
public static void main(String[] args) {
//a-z对应97-122
System.out.println((char)(int)(Math.random() * 26 + 97));
}
}
给出下面语句的输出结果。
System.out.println('a' < 'b');
System.out.println('a' <= 'A');
System.out.println('a' > 'b');
System.out.println('a' >= 'A');
System.out.println('a' == 'a');
System.out.println('a' != 'b');
true
false
false
true
true
true
4.4习题
假设s1、s2和S3是三个字符串,下列表达式的结果是什么?
String s1 = "Welcome to Java";
String s2 = "Programming is fun";
String s3 = "Welcome to Java";
//“==”只会判断2个字符串是否指向同一个对象
//“equals”会先判断2个字符串是否指向同一个对象,如果不是,再逐一比较字符数组(字符串类是用字符数组实现的)
//简单的字面赋值时,相同的字符串会指向同一个对象
s1 == s2 //false
s1 == s3 //true
s1.equals(s2) //false
s1.equals(s3) //true
//方法“compareTo”返回的实际值是依据sl和s2从左到右数第一个不同字符之间的距离得出的
s1.compareTo(s2) //7
s2.compareTo(s3) //-7
s2.compareTo(s2) //0
//方法s.charAt(index)可用于提取字符串s中的某个位置(用数字表示)的字符,其中下标index的取值范围在0 - s.length() - l之间。
s1.charAt(0) //W
//在字符串中找出指定的字符或一个子串(用字符表示),没有匹配返回-1
s1.indexOf('j') //-1
s1.indexOf("to") //8
s1.lastIndexOf('a') //14
s1.lastIndexOf("o",15) //9
//返回字符串长度,目前只有length方法是从1开始数,其他都是从0开始数
s1.length() //15
//单个参数返回该参数以后的所有内容,否则返回第一个参数到第二个参数-1的所有内容
s1.substring(5) //me to Java
s1.substring(5, 11) //me to
//字符串是否以特定的前缀开始
s1.startsWith("Wel") //true
s1.endsWith("Java") //true
s1.toLowerCase() //welcome to java
s1.toUpperCase() //WELCOME TO JAVA
//将本字符串和字符串s2连接,返回一个新字符串
s1.concat(s2) //Welcome to JavaProgramming is fun
//如果s2是该字符串的子字符串,返回true
s1.contains(s2) //false
//返回一个新字符串,去掉了两边的空白宇符
"\t Wel \t".trim() //Wel
假设s1、S2是两个字符串,以下语句或者表达式中哪些是错误的?
String s = "Welcome to Java"; //正确
String s3 = s1 + s2; //正确
String s3 = s1 - s2; //错误
s1 == s2; //boolean表达式不可以单独存在
s1 >= s2; //boolean表达式不可以单独存在
s1.compareTo(s2); //正确
int i = s1.length(); //正确
char c = s1(0); //没有这样的查找字符串方法
char c = s1.charAt(s1.length()); //正确
给出下列语句的输出(编写程序验证你的结果)
//有字符+数字,字符转型为数字并相加
//有字符串+数字,数字会转换成字符串,按顺序直接相连(有括号先算括号)
System.out.println('1' + 1 + 1);
System.out.println('1' + 1);
System.out.println("1" + 1);
System.out.println("1" + 1 + 1);
System.out.println("1" + (1 + 1));
51
50
11
111
12
对下列表达式求值(编写程序验证你的结果)
//有字符串+字符+数字,按顺序直接相连,字符串优先级最高
System.out.println(1 + "Welcome " + 1 + 1);
System.out.println(1 + "Welcome " + (1 + 1));
System.out.println(1 + "Welcome " + ('\u0001' + 1));
System.out.println(1 + "Welcome" + 'a' + 1);
1Welcome 11
1Welcome 2
1Welcome 2
1Welcome a1
假设s1是“Welcome“而s2是“welcome“,为下面的陈述编写代码:
a. 检查s1和s2是否相等,然后将结果赋值给一个布尔变量isEqual。
boolean isEqual = s1.equals(s2);
b. 在忽略大小写的情况下检查s1和s2是否相等,然后将结果赋值给一个布尔变量isEqual。
boolean isEqual = s1.equalsIgnoreCase(s2);
c. 比较s1和s2,然后将结果赋值给一个整型变量×。
int x = s1.compareTo(s2);
d. 在忽略大小写的情况下比较s1和s2,然后将结果赋值给一个整型变量×
int x = s1.compareToIgnoreCase(s2);
e. 检查s1是否有前缀“AAA“,然后将结果赋值给一个布尔变量b。
boolean b = s1.startsWith("AAA");
f. 检查s1是否有后缀“AAA“,然后将结果赋值给一个布尔变量b。
boolean b = s1.endsWith("AAA");
g. 将s1的长度赋值给一个整型变量×。
int x = s1.length();
h. 将s1的第一个字符赋值给一个字符型变量×。
char x = s1.charAt(0);
i. 创建新字符串s3,它是s1和s2的组合。
String s3 = s1.concat(s2);
j. 创建s1的子串,下标从1开始。
String s3 = s1.substring(1);
k. 创建s1的子串,下标从1到4。
String s3 = s1.substring(1, 4);
l. 创建新字符串s3,它将s1转换为小写。
String s3 = s1.toLowerCase();
m. 创建新字符串s3,它将s1转换为大写。
String s3 = s1.toUpperCase();
n. 创建新字符串s3,它将s1两端的空白字符去掉。
String s3 = s1.trim();
o. 将s1中第一次出现的字符e的下标赋值给一个int型变量x。
int x = s1.indexOf("e");
p. 将s1中最后一次出现的字符串abc的下标赋值给一个int型变量x。
int x = s1.lastIndexOf("abc");
4.5习题
如果运行程序清单4-3,对于Set1, Set3, Set4输入1,对于Set2和Set5输入0,生日将是哪一天?
生日13号
4.6习题
输出布尔值、字符、十进制整数、浮点数和字符串的格式标识符分别是什么?
%b, %c, %d, $f, %s
下面的语句错在哪里?
System.out.printf("%5d %d", 1, 2, 3); //位数不匹配
System.out.printf("%5d %f", 1); //位数不匹配、格式不匹配
System.out.printf("%5d %f", 1, 2); //格式不匹配
给出下面语句的输出。
//%f表示输出小数点以后6位浮点数;%e表示输出小数点以后6位科学计数法
System.out.printf("amount is %f %e\n", 32.32, 32.32);
//5.2f表示在保留2位小数的前提下,输出5个字节浮点数;5.4表示在保留4位小数的前提下,输出5个字节科学计数法
System.out.printf ("amount is %5.2f %5.4e\n", 32.327, 32.32);
//%6b表示输出布尔值,在false值前加一个空格,在true值前加两个空格
System.out.printf("%6b\n", (1 > 2));
//%6s表示输出6个字节的字符串,结果少于6就左边加空格,多于6就忽略
System.out.printf("%6s\n", "Java");
//%-6b表示输出布尔值,在false值后加一个空格,在true值后加两个空格;%s表示格式化输出字符串
System.out.printf ("%-6b%s\n", (1 > 2) , "Java") ;
//%-8s表示输出8字节字符串,结果少于8在字符串后面补齐,大于8忽略
System.out.printf("%6b%-8s\n", (1 > 2), "Java");
amount is 32.320000 3.232000e+01
amount is 32.33 3.2320e+01
false
Java
false Java
falseJava
编程练习题
4.1 (几何: 五边形的面积) 编写程序,提示用户输人从五边形中心到顶点的距离 ,计算五边形的面积,如右图所示。
计算五边形面积的公示为:面积 = 5 × s 2 4 × t a n ( π 5 ) \frac{5 \times s^2}{4 \times tan(\frac{\pi}{5})} 4×tan(5π)5×s2,其中s是边长。边长可以使用公式 s = 2 r × s i n π 5 s = 2r \times sin\frac{\pi}{5} s=2r×sin5π计算,其中r是从五边形中心到顶点的距离。结果保留小数点后两位数字
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the length from the center to a vertex: ");
double r = input.nextDouble();
double s = 2 * r * Math.sin(Math.PI / 5);
double range = (5 * s * s) / (4 * Math.tan(Math.PI / 5));
System.out.printf("The area of the pentagon is %.2f", range);
}
}
Enter the length from the center to a vertex: 5.5
The area of the pentagon is 71.92
*4.2 (几何: 最大圆距离) 最大圆距离是指球面上两个点之间的距离。假设(x1, y1)和(x2, y2)是两个点的地理经纬度。两个点之间的最大圆距离可以使用以下公式计算 :
d = 半径 × a r c c o s ( s i n ( x 1 ) × s i n ( x 2 ) + c o s ( x 1 ) × c o s ( x 2 ) × c o s ( y 1 − y 2 ) ) d = 半径 \times arccos(sin(x1) \times sin(x2) + cos(x1) \times cos(x2) \times cos(y1 - y2)) d=半径×arccos(sin(x1)×sin(x2)+cos(x1)×cos(x2)×cos(y1−y2))
编写一个程序,提示用户以度为单位输入地球上两个点的经纬度,显示其最大圆距离值。地球的平均半径为 6 371.01km。注意,你需要使用 Math.toRadians方法将度转换为弧度值。公式中的经纬度是相对北边和西边的,使用负数表示相对南边和东边的度数。
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter point 1 (latitude and longitude) in degrees: ");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
System.out.print("Enter point 2 (latitude and longitude) in degrees: ");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
final double RADIUS = 6371.01;
double d = RADIUS * Math.acos(Math.sin(Math.toRadians(x1)) *
Math.sin(Math.toRadians(x2)) +
Math.cos(Math.toRadians(x1)) *
Math.cos(Math.toRadians(x2)) *
Math.cos(Math.toRadians(y1 - y2)));
System.out.print("The distance between the two points is " + d + " km");
}
}
Enter point 1 (latitude and longitude) in degrees: 39.55 -116.25
Enter point 2 (latitude and longitude) in degrees: 41.5 87.37
The distance between the two points is 10691.79183231593 km
*4.3 (几何: 估算面积) 从网址www.gps-data-team.com/map上面找到Georgia州的Atlanta、Florida 州的 Orlando、Georgia 州的Savannah、North Carolina 的Charlotte, 计算被这四个城市所围起来的区域的面积。(提示: 使用编程练习题4.2中的公式来计算两个城市之间的距离。将多边形分为两个三角形,使用编程练习题2.19中的公式计算三角形面积。)
public class Main {
public static void main(String[]args){
/*
* Atlanta 33.7488° N, 84.3877° W
* Orlando 28.5384° N, 81.3789° W
* Savannah 32.0809° N, 81.0912° W
* Charlotte 35.2271° N, 80.8431° W
* AOS & ASC
*/
final double RADIUS = 6371.01;
final double a1 = 33.7488;
final double a2 = 84.3877;
final double o1 = 28.5384;
final double o2 = 81.3789;
final double s1 = 32.0809;
final double s2 = 81.0912;
final double c1 = 35.2271;
final double c2 = 80.8431;
final double d_AO = RADIUS * Math.acos(Math.sin(Math.toRadians(a1)) *
Math.sin(Math.toRadians(o1)) +
Math.cos(Math.toRadians(a1)) *
Math.cos(Math.toRadians(o1)) *
Math.cos(Math.toRadians(a2 - o2)));
final double d_AS = RADIUS * Math.acos(Math.sin(Math.toRadians(a1)) *
Math.sin(Math.toRadians(s1)) +
Math.cos(Math.toRadians(a1)) *
Math.cos(Math.toRadians(s1)) *
Math.cos(Math.toRadians(a2 - s2)));
final double d_OS = RADIUS * Math.acos(Math.sin(Math.toRadians(o1)) *
Math.sin(Math.toRadians(s1)) +
Math.cos(Math.toRadians(o1)) *
Math.cos(Math.toRadians(s1)) *
Math.cos(Math.toRadians(o2 - s2)));
final double d_AC = RADIUS * Math.acos(Math.sin(Math.toRadians(a1)) *
Math.sin(Math.toRadians(c1)) +
Math.cos(Math.toRadians(a1)) *
Math.cos(Math.toRadians(c1)) *
Math.cos(Math.toRadians(a2 - c2)));
final double d_SC = RADIUS * Math.acos(Math.sin(Math.toRadians(s1)) *
Math.sin(Math.toRadians(c1)) +
Math.cos(Math.toRadians(s1)) *
Math.cos(Math.toRadians(c1)) *
Math.cos(Math.toRadians(s2 - c2)));
final double sAOS = (d_AO + d_AS + d_OS) / 2;
final double rangeAOS = Math.pow(sAOS * (sAOS - d_AO) * (sAOS - d_AS) * (sAOS - d_OS), 0.5);
final double sASC = (d_AS + d_AC + d_SC) / 2;
final double rangeASC = Math.pow(sASC * (sASC - d_AS) * (sASC - d_AC) * (sASC - d_SC), 0.5);
System.out.print("The range of the 4-cities area is " + (rangeAOS + rangeASC));
}
}
The range of the 4-cities area is 118159.33991693535
4.4 (几何: 六边形面积) 六边形面积可以通过下面公式计算(s是边长):
面积 = 6 × s 2 4 × t a n ( π 6 ) 面积 = \frac{6 \times s^2}{4 \times tan(\frac{\pi}{6})} 面积=4×tan(6π)6×s2
编写程序,提示用户输入六边形的边长,然后显示它的面积。
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the side: ");
double s = input.nextDouble();
double range = (6 * s * s) / (4 * Math.tan(Math.PI / 6));
System.out.printf("The area of the hexagon is %.2f", range);
}
}
Enter the side: 5.5
The area of the hexagon is 78.59
*4.5 (几何: 正多边形的面积) 正多边形是一个n条边的多边形,它每条边的长度都相等,而且所有角的度数也相等(即多边形既等边又等角)。计算正多边形面积的公式是:
面积
=
n
×
s
2
4
×
t
a
n
(
π
s
)
面积 = \frac{n \times s^2}{4 \times tan(\frac{\pi}{s})}
面积=4×tan(sπ)n×s2
这里,s是边长。编写一个程序,提示用户输人边的个数以及正多边形的边长,然后显示它的面积
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of sides: ");
int num = input.nextInt();
System.out.print("Enter the side: ");
double s = input.nextDouble();
double range = (num * s * s) / (4 * Math.tan(Math.PI / num));
System.out.printf("The area of the hexagon is %.2f", range);
}
}
Enter the number of sides: 5
Enter the side: 6.5
The area of the hexagon is 72.69
*4.6 (圆上的随机点) 编写一个程序,产生一个圆心在(0, 0)、半径为40的圆上面的3个随机点,显示由这三个随机点组成的三角形的三个角的度数,如图4-4a所示。(提示: 产生0 - 2 π \pi π 之间的一个以弧度为单位的随机角度 a a a, 如图 4-4b 所示,则由这个角度所确定的点为 ( r × c o s ( a ) , r × s i n ( a ) ) (r \times cos(a), r \times sin(a)) (r×cos(a),r×sin(a)))。
public class Main {
public static void main(String[] args) {
// 随机生成三个角度
double angle1 = Math.random() * 2 * Math.PI;
double angle2 = Math.random() * 2 * Math.PI;
double angle3 = Math.random() * 2 * Math.PI;
// 获取三个点的坐标
final double R = 40.0;
double x1 = R * Math.cos(angle1), y1 = R * Math.sin(angle1);
double x2 = R * Math.cos(angle2), y2 = R * Math.sin(angle2);
double x3 = R * Math.cos(angle3), y3 = R * Math.sin(angle3);
// 求出三条边的长度
double l1 = Math.pow((Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2)), 0.5);
double l2 = Math.pow((Math.pow(x1-x3, 2) + Math.pow(y1-y3, 2)), 0.5);
double l3 = Math.pow((Math.pow(x2-x3, 2) + Math.pow(y2-y3, 2)), 0.5);
// 求出每个角的角度
double A = Math.toDegrees(Math.acos((l3 * l3 - l1 * l1 - l2 * l2) / (-2 * l1 * l2)));
double B = Math.toDegrees(Math.acos((l2 * l2 - l1 * l1 - l3 * l3) / (-2 * l1 * l3)));
double C = Math.toDegrees(Math.acos((l1 * l1 - l2 * l2 - l3 * l3) / (-2 * l2 * l3)));
// 输出结果
System.out.printf("第一个角角度为: %.2f, 第二个角角度为: %.2f, 第三个角角度为%.2f", A, B, C);
}
}
第一个角角度为: 102.52, 第二个角角度为: 17.48, 第三个角角度为60.00
*4.7 (顶点坐标) 假设一个正五边形的中心位于(0, 0),其中一个点位于0点位置,如图4-4c所示。编写一个程序,提示用户输入正五边形外切圆的半径,显示正五边形上五个顶点的坐标。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 获取半径
Scanner input = new Scanner(System.in);
System.out.print("Enter the radius of the bounding circle: ");
double r = input.nextDouble();
// 求顶点到x轴夹角的几个特殊值
double angleUp = Math.toRadians(90 - 360 / 5);
double angleDown = Math.toRadians((2 * 360) / 5 - 90);
// 求出5个顶点的x、y坐标
double xp1 = r * Math.cos(angleUp), yp1 = r * Math.sin(angleUp);
double xp2 = 0, yp2 = r;
double xp3 = -r * Math.cos(angleUp), yp3 = r * Math.sin(angleUp);
double xp4 = -r * Math.cos(angleDown), yp4 = -r * Math.sin(angleDown);
double xp5 = r * Math.cos(angleDown), yp5 = -r * Math.sin(angleDown);
// 输出数据
System.out.println("The coordinates of five points on the pentagon are");
System.out.printf("(%.2f, %.2f)", xp1, yp1);
System.out.printf("\n(%.2f, %.2f)", xp2, yp2);
System.out.printf("\n(%.2f, %.2f)", xp3, yp3);
System.out.printf("\n(%.2f, %.2f)", xp4, yp4);
System.out.printf("\n(%.2f, %.2f)", xp5, yp5);
}
}
Enter the radius of the bounding circle: 100
The coordinates of five points on the pentagon are
(95.11, 30.90)
(0.00, 100.00)
(-95.11, 30.90)
(-58.78, -80.90)
(58.78, -80.90)
*4.8 (给出ASCII码对应的字符)编写一个程序,得到一个ASCII码的输入(0-127之间的一个整数),然后显示该字符
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an ASCII code: ");
int code = input.nextInt();
System.out.print("The character for ASCII code " + code + " is " + (char)code);
input.close();
}
}
Enter an ASCII code: 69
The character for ASCII code 69 is E
*4.9 (给出字符的Unicode码) 编写一个程序,得到一个字符的输入,然后显示其Unicode值
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
//Java没有提供char类型的输入,因此用String类型.charAt()
String code = input.nextLine();
char x = code.charAt(0);
System.out.print("The Unicode for the character " + x + " is " + (int)x);
input.close();
}
}
Enter a character: E
The Unicode for the character E is 69
*4.10 (猜测生曰) 改写程序清单4-3,提示用户输入字符Y代表 “是”,输入N代表 “不是”,代替之前输入1表示 “是” 和0表示 “不是”
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String set1 =
" 1 3 5 7\n" +
" 9 11 13 15\n" +
"17 19 21 23\n" +
"25 27 29 31";
String set2 =
" 2 3 6 7\n" +
"10 11 14 15\n" +
"18 19 22 23\n" +
"26 27 30 31";
String set3 =
" 4 5 6 7\n" +
"12 13 14 15\n" +
"20 21 22 23\n" +
"28 29 30 31";
String set4 =
" 8 9 10 11\n" +
"12 13 14 15\n" +
"24 25 26 27\n" +
"28 29 30 31";
String set5 =
"16 17 18 19\n" +
"20 21 22 23\n" +
"24 25 26 27\n" +
"28 29 30 31\n";
int day = 0;
//Create a Scanner
Scanner input = new Scanner(System.in);
//Prompt the user to answer questions
System.out.print("Is your birthday in Set1?\n");
System.out.print(set1);
System.out.print("\nEnter N for No and Y for Yes: ");
String answer = input.next();
if (answer.equals("Y"))
day += 1;
//Prompt the user to answer questions
System.out.print("\nIs your birthday in Set2?\n");
System.out.print(set2);
System.out.print("\nEnter N for No and Y for Yes: ");
answer = input.next();
if (answer.equals("Y"))
day += 2;
//Prompt the user to answer questions
System.out.print("\nIs your birthday in Set3?\n");
System.out.print(set3);
System.out.print("\nEnter N for No and Y for Yes: ");
answer = input.next();
if (answer.equals("Y"))
day += 4;
//Prompt the user to answer questions
System.out.print("\nIs your birthday in Set4?\n");
System.out.print(set4);
System.out.print("\nEnter N for No and Y for Yes: ");
answer = input.next();
if (answer.equals("Y"))
day += 8;
//Prompt the user to answer questions
System.out.print("\nIs your birthday in Set5?\n");
System.out.print(set5);
System.out.print("\nEnter N for No and Y for Yes: ");
answer = input.next();
if (answer.equals("Y"))
day+=16;
System.out.println("\nYour birthday is " + day + "!");
}
}
Is your birthday in Set1?
1 3 5 7
9 11 13 15
17 19 21 23
25 27 29 31
Enter N for No and Y for Yes: Y
Is your birthday in Set2?
2 3 6 7
10 11 14 15
18 19 22 23
26 27 30 31
Enter N for No and Y for Yes: Y
Is your birthday in Set3?
4 5 6 7
12 13 14 15
20 21 22 23
28 29 30 31
Enter N for No and Y for Yes: Y
Is your birthday in Set4?
8 9 10 11
12 13 14 15
24 25 26 27
28 29 30 31
Enter N for No and Y for Yes: Y
Is your birthday in Set5?
16 17 18 19
20 21 22 23
24 25 26 27
28 29 30 31
Enter N for No and Y for Yes: Y
Your birthday is 31!
*4.11 (十进制转十六进制) 编写一个程序,提示用户输人0-15之间的一个整数,显示其对应的十六进制数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal value (0 to 15): ");
int answer = input.nextInt();
if (answer < 0 || answer > 15)
System.out.println(answer + " is an invalid input");
else if (answer >= 0 && answer <= 9)
System.out.println("The hex value is " + answer);
else
switch(answer) {
case(10):
System.out.println("The hex value is A");
break;
case(11):
System.out.println("The hex value is B");
break;
case(12):
System.out.println("The hex value is C");
break;
case(13):
System.out.println("The hex value is D");
break;
case(14):
System.out.println("The hex value is E");
break;
case(15):
System.out.println("The hex value is F");
}
input.close();
}
}
Enter a decimal value (0 to 15): 33
33 is an invalid input
4.12 (十六进制转二进制) 编写一个程序,提示用户输人一个十六进制数,显示其对应的二进制数。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex digit: ");
String answer = input.next();
if (answer.length() > 1 || answer.charAt(0) > 'F')
System.out.println(answer + " is an invalid input");
else
switch(answer.charAt(0)) {
case('0'):
System.out.println("The binary value is 0000");
break;
case('1'):
System.out.println("The binary value is 0001");
break;
case('2'):
System.out.println("The binary value is 0010");
break;
case('3'):
System.out.println("The binary value is 0011");
break;
case('4'):
System.out.println("The binary value is 0100");
break;
case('5'):
System.out.println("The binary value is 0101");
break;
case('6'):
System.out.println("The binary value is 0110");
break;
case('7'):
System.out.println("The binary value is 0111");
break;
case('8'):
System.out.println("The binary value is 1000");
break;
case('9'):
System.out.println("The binary value is 1001");
break;
case('A'):
System.out.println("The binary value is 1010");
break;
case('B'):
System.out.println("The binary value is 1011");
break;
case('C'):
System.out.println("The binary value is 1100");
break;
case('D'):
System.out.println("The binary value is 1101");
break;
case('E'):
System.out.println("The binary value is 1110");
break;
case('F'):
System.out.println("The binary value is 1111");
}
input.close();
}
}
Enter a hex digit: G
G is an invalid input
*4.13 (利断元音还是辅音) 编写一个程序,提示用户输入一个字母,判断该字母是元音还是辅音
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a letter grade: ");
String answer = input.next();
char x = answer.charAt(0);
if (answer.length() == 1 && x >= 'A' && x <= 'Z')
switch (x) {
case('A'): System.out.print(x + " is a vowel"); break;
case('E'): System.out.print(x + " is a vowel"); break;
case('I'): System.out.print(x + " is a vowel"); break;
case('O'): System.out.print(x + " is a vowel"); break;
case('U'): System.out.print(x + " is a vowel"); break;
default: System.out.print(x + " is a consonant");
}
else if (answer.length() == 1 && x >= 'a' && x <= 'z')
switch (x) {
case('a'): System.out.print(x + " is a vowel"); break;
case('e'): System.out.print(x + " is a vowel"); break;
case('i'): System.out.print(x + " is a vowel"); break;
case('o'): System.out.print(x + " is a vowel"); break;
case('u'): System.out.print(x + " is a vowel"); break;
default: System.out.print(x + " is a consonant");
}
else
System.out.print(answer + " is an invalid input");
input.close();
}
}
Enter a letter grade: G
G is a consonant
*4.14 (转換字母等级为數字) 编写一个程序,提示用户输入一个字母等级A、B、C、D或者F, 显示对应的数字值4、3、2、1 或者 0。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a letter grade: ");
String answer = input.next();
char x = answer.charAt(0);
if (answer.length() == 1 && x >= 'A' && x <= 'F')
switch (x) {
case('A'): System.out.print("The numeric value for grade A is 4"); break;
case('B'): System.out.print("The numeric value for grade B is 3"); break;
case('C'): System.out.print("The numeric value for grade C is 2"); break;
case('D'): System.out.print("The numeric value for grade D is 1"); break;
case('F'): System.out.print("The numeric value for grade F is 0"); break;
default: System.out.print(answer + " is an invalid input");
}
else
System.out.print(answer + " is an invalid input");
input.close();
}
}
Enter a letter grade: F
The numeric value for grade F is 0
*4.15 (电话键盘) 电话上的国际标准字母 / 数字映射如下所示: 编写一个程序,提示用户输入一个字母,然后显示对应的数字
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a letter: ");
String answer = input.next();
char x = answer.toUpperCase().charAt(0);
if (answer.length() == 1)
switch (x) {
case('A'): System.out.print("The corresponding number is 2"); break;
case('B'): System.out.print("The corresponding number is 2"); break;
case('C'): System.out.print("The corresponding number is 2"); break;
case('D'): System.out.print("The corresponding number is 3"); break;
case('E'): System.out.print("The corresponding number is 3"); break;
case('F'): System.out.print("The corresponding number is 3"); break;
case('G'): System.out.print("The corresponding number is 4"); break;
case('H'): System.out.print("The corresponding number is 4"); break;
case('I'): System.out.print("The corresponding number is 4"); break;
case('J'): System.out.print("The corresponding number is 5"); break;
case('K'): System.out.print("The corresponding number is 5"); break;
case('L'): System.out.print("The corresponding number is 5"); break;
case('M'): System.out.print("The corresponding number is 6"); break;
case('N'): System.out.print("The corresponding number is 6"); break;
case('O'): System.out.print("The corresponding number is 6"); break;
case('P'): System.out.print("The corresponding number is 7"); break;
case('Q'): System.out.print("The corresponding number is 7"); break;
case('R'): System.out.print("The corresponding number is 7"); break;
case('S'): System.out.print("The corresponding number is 7"); break;
case('T'): System.out.print("The corresponding number is 8"); break;
case('U'): System.out.print("The corresponding number is 8"); break;
case('V'): System.out.print("The corresponding number is 8"); break;
case('W'): System.out.print("The corresponding number is 9"); break;
case('X'): System.out.print("The corresponding number is 9"); break;
case('Y'): System.out.print("The corresponding number is 9"); break;
case('Z'): System.out.print("The corresponding number is 9"); break;
default: System.out.print(answer + " is an invalid input");
}
else
System.out.print(answer + " is an invalid input");
input.close();
}
}
Enter a letter: G
The corresponding number is 4
4.16 (随机字符) 编写一个程序,使用Math.random()方法显示一个随机的大写字母。
public class Main {
public static void main(String[] args) {
//65,90
int x = (int)(Math.random() * 26 + 65);
char z = (char)x;
System.out.print(z);
}
}
D
*4.17 ( —个月中的日期) 编写一个程序,提示用户输人一个年份和一个月份名称的前三个字母(第一个字母使用大写形式),显示该月中的天数
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
System.out.print("Enter a Month: ");
String month = input.next();
//普通年丰能被4整除且不能被100整除是闰年
//世纪年份能被400整除是闰年
if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0))
switch(month) {
case("Jan"): System.out.println(month + " " + year + " has 31 days"); break;
case("Feb"): System.out.println(month + " " + year + " has 29 days"); break;
case("Mar"): System.out.println(month + " " + year + " has 31 days"); break;
case("Apr"): System.out.println(month + " " + year + " has 30 days"); break;
case("May"): System.out.println(month + " " + year + " has 31 days"); break;
case("Jun"): System.out.println(month + " " + year + " has 30 days"); break;
case("Jul"): System.out.println(month + " " + year + " has 31 days"); break;
case("Aug"): System.out.println(month + " " + year + " has 31 days"); break;
case("Sep"): System.out.println(month + " " + year + " has 30 days"); break;
case("Oct"): System.out.println(month + " " + year + " has 31 days"); break;
case("Nov"): System.out.println(month + " " + year + " has 30 days"); break;
case("Dec"): System.out.println(month + " " + year + " has 31 days"); break;
}
else
switch(month) {
case("Jan"): System.out.println(month + " " + year + " has 31 days"); break;
case("Feb"): System.out.println(month + " " + year + " has 28 days"); break;
case("Mar"): System.out.println(month + " " + year + " has 31 days"); break;
case("Apr"): System.out.println(month + " " + year + " has 30 days"); break;
case("May"): System.out.println(month + " " + year + " has 31 days"); break;
case("Jun"): System.out.println(month + " " + year + " has 30 days"); break;
case("Jul"): System.out.println(month + " " + year + " has 31 days"); break;
case("Aug"): System.out.println(month + " " + year + " has 31 days"); break;
case("Sep"): System.out.println(month + " " + year + " has 30 days"); break;
case("Oct"): System.out.println(month + " " + year + " has 31 days"); break;
case("Nov"): System.out.println(month + " " + year + " has 30 days"); break;
case("Dec"): System.out.println(month + " " + year + " has 31 days"); break;
}
input.close();
}
}
Enter a year: 2000
Enter a Month: Feb
Feb 2000 has 29 days
*4.18 (学生的专业和状况) 编写一个程序,提示用户输入两个字符,显示这两个字符代表的专业以及状况。第一个字符表示专业,第二个是一个数字字符1、2、3、4, 分别表示该学生是大一、大二、 大三还是大四。假设下面的字符用于表示专业: M:数学 C:计算机科学 I:信息技术
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter two characters: ");
String academic = input.nextLine();
if ((academic.charAt(0) == 'M' || academic.charAt(0) == 'C' || academic.charAt(0) == 'I') &&
academic.charAt(1) == '1' || academic.charAt(1) == '2' || academic.charAt(1) == '3' || academic.charAt(1) == '4') {
switch(academic.charAt(0)) {
case('M'): System.out.print("Mathematics "); break;
case('C'): System.out.print("Computer Science "); break;
case('I'): System.out.print("Information Technology "); break;
}
switch(academic.charAt(1)) {
case('1'): System.out.print("Year 1"); break;
case('2'): System.out.print("Year 2"); break;
case('3'): System.out.print("Year 3"); break;
case('4'): System.out.print("Year 4"); break;
}
}
else
System.out.print("Invalid Input");
input.close();
}
}
Enter two characters: A9
Invalid Input
4.19 (商业:检测 ISBN-10) 改写编程练习题3.9, 将ISBN号作为一个字符串输入
import java.util.*;
public class Main{
public static void main(String[] args){
//读取整数字符串输入
Scanner input = new Scanner(System.in);
System.out.print("Enter the first 9 digits of ISBN-10: ");
String ISBN9 = input.next();
//使用数组将整数字符串中的每个元素提取成整数
int[] number = new int[ISBN9.length()];
for (int x = 0; x < ISBN9.length(); x++) {
number[x] = (int)ISBN9.charAt(x) - (int)('0');
}
//提取数组中的每个整数
int a1 = number[0];
int a2 = number[1];
int a3 = number[2];
int a4 = number[3];
int a5 = number[4];
int a6 = number[5];
int a7 = number[6];
int a8 = number[7];
int a9 = number[8];
//计算第十位ISBN
if ((a1 + a2 * 2 + a3 * 3 + a4 * 4 + a5 * 5 + a6 * 6 + a7 * 7 + a8 * 8 + a9 * 9) % 11 == 10)
System.out.println("The ISBN-10 is " + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + "X");
else
System.out.print("The ISBN-10 is " + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8+ a9 +
((a1 + a2 * 2 + a3 * 3 + a4 * 4 + a5 * 5 + a6 * 6 + a7 * 7 + a8 * 8 + a9 * 9) % 11));
input.close();
}
}
Enter the first 9 digits of ISBN-10: 013031997
The ISBN-10 is 013031997X
4.20 (字符串处理) 编写一个程序,提示用户输入一个字符串,显示它的长度和第一个字符
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String string = input.next();
System.out.println("The length of this string is " + string.length() + ". And the first char is " + string.charAt(0));
input.close();
}
}
Enter a string: 452gwsfv
The length of this string is 8. And the first char is 4
*4.21 (检查 SSN) 编写一个程序,提示用户输入一个社保号码,它的格式是 DDD-DD-DDDD, 其中D是一个数字。你的程序应该判断输入是否合法。
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a SSN: ");
String ssn = input.next();
//先判断length是否为11,不是11直接报告打印不正确
//如果直接判定char s1-11,当length不是11的时候,会导致运行时错误
if (ssn.length() == 11) {
char s1 = ssn.charAt(0);
char s2 = ssn.charAt(1);
char s3 = ssn.charAt(2);
char s4 = ssn.charAt(3);
char s5 = ssn.charAt(4);
char s6 = ssn.charAt(5);
char s7 = ssn.charAt(6);
char s8 = ssn.charAt(7);
char s9 = ssn.charAt(8);
char s10 = ssn.charAt(9);
char s11 = ssn.charAt(10);
if (Character.isDigit(s1) && Character.isDigit(s2) && Character.isDigit(s3) &&
s4 == '-' &&
Character.isDigit(s5) && Character.isDigit(s6) &&
s7 == '-' &&
Character.isDigit(s8) && Character.isDigit(s9) && Character.isDigit(s10) && Character.isDigit(s11))
System.out.print(ssn + " is a valid social security number");
else
System.out.print(ssn + " is an invalid social security number");
}
else
System.out.print(ssn + " is an invalid social security number");
input.close();
}
}
Enter a SSN: 341-124
341-124 is an invalid social security number
4.22 (检测子串) 编写一个程序,提示用户输入两个字符串,检测第二个字符串是否是第一个字符串的子串。
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter string s1: ");
String s1 = input.next();
System.out.print("Enter string s2: ");
String s2 = input.next();
if (s1.contains(s2))
System.out.print(s2 + " is a substring of " + s1);
else
System.out.print(s2 + " is not a substring of " + s1);
input.close();
}
}
Enter string s1: 123
Enter string s2: 1234
1234 is not a substring of 123
*4.23 (财务应用:酬金) 编写一个程序,读取下面的信息,然后输出一个酬金声明:
雇员姓名(如:Smith)
每周的工作小时数(如,10小时)
每小时的酬金(如,9.75 美元)
联邦所得税税率(如 ,20% )
州所得税税率(如,9% )
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter employee's name: ");
String name = input.next();
System.out.print("Enter number of hours worked in a week: ");
double hours = input.nextDouble();
System.out.print("Enter hourly pay rate: ");
double rate = input.nextDouble();
System.out.print("Enter federal tax withholding rate: ");
double fedTax = input.nextDouble();
System.out.print("Enter state tax withholding rate: ");
double staTax = input.nextDouble();
System.out.println("Employee name: " + name);
System.out.println("Hours worked: " + hours);
System.out.println("Pay rate: $" + rate);
System.out.println("Gross pay: $" + (hours * rate));
System.out.println("Deductions: ");
System.out.println(" Federal Withholding (" + fedTax + ") : $" + (hours * rate * fedTax));
System.out.println(" State Withholding (" + fedTax + ") : $" + (hours * rate * staTax));
System.out.println(" Total Deduction: $" + ((hours * rate * fedTax) + (hours * rate * staTax)));
System.out.print("Net pay: $" + ((hours * rate) - (hours * rate * fedTax) - (hours * rate * staTax)));
input.close();
}
}
Enter employee's name: Smith
Enter number of hours worked in a week: 10
Enter hourly pay rate: 9.75
Enter federal tax withholding rate: 0.2
Enter state tax withholding rate: 0.09
Employee name: Smith
Hours worked: 10.0
Pay rate: 9.75
Gross pay 97.5
Deductions:
Federal Withholding (0.2) : 19.5
State Withholding (0.2) : 8.775
Total Deduction: 28.275
Net pay: 69.225
*4.24 (对三个城市排序) 编写一个程序,提示用户输入三个城市名称,然后以升序进行显示。
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter first city's name: ");
String name1 = input.nextLine();
System.out.print("Enter second city's name: ");
String name2 = input.nextLine();
System.out.print("Enter third city's name: ");
String name3 = input.nextLine();
String[] names = {name1, name2, name3};
Arrays.sort(names);
System.out.print("The three cities in alphabetical order are ");
for (int i = 0; i < names.length; i++) {
System.out.print(names[i] + " ");
}
input.close();
}
}
Enter first city's name: Las Vegas
Enter second city's name: Atlanta
Enter third city's name: London
The three cities in alphabetical order are Atlanta Las Vegas London
*4.25 (生成车牌号码) 假设一个车牌号码由三个大写字母和后面的四个数字组成。编写一个程序生成一个车牌号码。
public class Main{
public static void main(String[] args){
//A-Z:65-90
int a1 = (int)(Math.random() * 26 + 65);
int a2 = (int)(Math.random() * 26 + 65);
int a3 = (int)(Math.random() * 26 + 65);
//0-9:48-57
int a4 = (int)(Math.random() * 10 + 48);
int a5 = (int)(Math.random() * 10 + 48);
int a6 = (int)(Math.random() * 10 + 48);
int a7 = (int)(Math.random() * 10 + 48);
char b1 = (char)a1;
char b2 = (char)a2;
char b3 = (char)a3;
char b4 = (char)a4;
char b5 = (char)a5;
char b6 = (char)a6;
char b7 = (char)a7;
System.out.print("" + b1 + b2 + b3 + b4 + b5 + b6 + b7);
}
}
MNT7168
*4.26 (财务应用: 货币单位)改写程序清单2-10, 解决将 float 型值转换为 int 型值时可能会造成精度损失的问题。读取的输人值是一个字符串,比如"11.56"。你的程序应该应用indexOf和substring方法抽取小数点前的美元数量,以及小数点后面的美分数量。
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Input dollar amount: $");
String money = input.nextLine();
int x = money.indexOf('.');
String dollar = money.substring(0, x);
String penny = money.substring(x + 1);
System.out.print("Your total money is " + dollar + " dollars and " + penny + " pennies");
input.close();
}
}
Input dollar amount: $11.56
Your total money is 11 dollars and 56 pennies