Java从入门到精通章节练习题——第十一章
Exercise 1 打印日历
综合练习1:打印日历 使用Calendar类计算并打印当前月份的日历
package org.hj.chapter11;
import java.util.Calendar;
import java.util.Date;
public class PrintCalendar {
/**
* 综合练习1:打印日历 使用Calendar类计算并打印当前月份的日历
*/
public static void main(String[] args) {
// 获取当前时间
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; // 注意月份是从0开始的,所以要加1
// 打印日历头部
System.out.printf("%d年%d月\n", year, month);
System.out.println("日\t一\t二\t三\t四\t五\t六");
// 获取当前月份第一天是星期几
cal.set(Calendar.DAY_OF_MONTH, 1);
int firstDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
// 打印当前月份的日历
int day = 1;
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 7; j++) {
if (i == 1 && j < firstDayOfWeek) {
System.out.print("\t"); // 打印空格占位
} else if (day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
break;
} else {
System.out.printf("%d\t", day++);
}
}
System.out.println();
}
}
}
Exercise 2 勾股定理数
综合练习2:勾股定理数 找出1~100中都有哪些数符合勾股定理。例如3、4、5。
勾股定理指的是:直角三角形的两条直角边的平方和等于斜边的平方,即a² + b² = c²。其中a、b、c为正整数,且a < b < c。因此,我们可以使用双重循环来遍历所有可能的组合,判断是否符合勾股定理:
package org.hj.chapter11;
public class PythagoreanTheorem {
/**
* 综合练习2:勾股定理数 找出1~100中都有哪些数符合勾股定理。例如3、4、5。
*/
/**
* 勾股定理指的是:直角三角形的两条直角边的平方和等于斜边的平方,
* 即a² + b² = c²。其中a、b、c为正整数,且a < b < c。
* 因此,我们可以使用双重循环来遍历所有可能的组合,判断是否符合勾股定理:
*/
public static void main(String[] args) {
for (int a = 1; a <= 100; a++) {
for (int b = a + 1; b <= 100; b++) {
for (int c = b + 1; c <= 100; c++) {
if (a * a + b * b == c * c) {
System.out.printf("%d、%d、%d\n", a, b, c);
}
}
}
}
}
}
Exercise 3 坐标移动
综合练习3:坐标移动 一个小球在直角坐标系中的坐标位置是(15,4),它向与竖直线成30°角的东北方向移动了100个单位的距离,请问小球移动后的坐标是多少?
可以将向量(100cos30°, 100sin30°)加到原始坐标(15, 4)上,得到移动后的坐标。
package org.hj.chapter11;
public class CoordinateMovement {
/**
* 综合练习3:坐标移动 一个小球在直角坐标系中的坐标位置是(15,4),
* 它向与竖直线成30°角的东北方向移动了100个单位的距离,请问小球移动后的坐标是多少?
*
* 可以将向量(100cos30°, 100sin30°)加到原始坐标(15, 4)上,得到移动后的坐标。
*/
public static void main(String[] args) {
double x = 15 + 100 * Math.sin(Math.toRadians(30)); // sin函数参数为弧度制,需将角度转换为弧度
double y = 4 + 100 * Math.cos(Math.toRadians(30)); // cos函数参数为弧度制,需将角度转换为弧度
System.out.printf("移动后的坐标为:(%.2f, %.2f)", x, y);
}
}