1.输出日历 使用Calendar类计算并输出当前月份的日历,效果如下图所示:
答案:
import java.util.Calendar;
public class MyCalendar {
public static void main(String[] args) {
StringBuilder str = new StringBuilder(); // 用于记录输出内容
Calendar c = Calendar.getInstance(); // 获取当期日历对象
int year = c.get(Calendar.YEAR); // 当前年
int month = c.get(Calendar.MONTH) + 1; // 当前月
c.add(Calendar.MONTH, 1); // 向后加一个月
c.set(Calendar.DAY_OF_MONTH, 0); // 日期变为上个月最后一天
int dayCount = c.get(Calendar.DAY_OF_MONTH); // 获取月份总天数
c.set(Calendar.DAY_OF_MONTH, 1); // 将日期设为月份第一天
int week = c.get(Calendar.DAY_OF_WEEK); // 获取第一天的星期数
int day = 1; // 从第一天开始
str.append("\t\t" + year + "-" + month + "\n"); // 显示年月
str.append("日\t一\t二\t三\t四\t五\t六\n"); // 星期列
for (int i = 1; i <= 7; i++) { // 先打印空白日期
if (i < week) { // 如果当前星期小于第一天的星期
str.append("\t"); // 不记录日期
} else {
str.append(day + "\t"); // 记录日期
day++;// 日期递增
}
}
str.append("\n"); // 换行
int i = 1; // 7天换一行功能用到的临时变量
while (day <= dayCount) { // 如果当前天数小于等于最大天数
str.append(day + "\t");// 记录日期
if (i % 7 == 0) {// 如果输出到第七天
str.append("\n");// 换行
}
i++;// 临时变量递增
day++;// 天数递增
}
System.out.println(str);// 打印日历
}
}
2.勾股定理数 找出1~100都有哪些数符合勾股定理,如3,4,5。
答案:
public class Demo {
public static void main(String[] args) {
for (int a = 1; a <= 100; a++) {
for (int b = 1; b <= 100; b++) {
for (int c = 1; c <= 100; c++) {
if (Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2)) {
System.out.println(a + "," + b + "," + c);
}
}
}
}
}
}
3.坐标移动 一个小球在直角坐标系中的坐标位置(15,4),它向与竖直线成30°角的东北方向移动了100个单位的距离,请问小球移动后的坐标是多少?
答案:
public class Demo {
public static void main(String[] args) {
double distance = 100;
int x1 = 15, y1 = 14;
int angle = 30;
double distance_H = distance * Math.sin(Math.toRadians(angle));
double distance_V = distance * Math.cos(Math.toRadians(angle));
int x2 = x1 + (int) Math.round(distance_H);
int y2 = y1 + (int) Math.round(distance_V);
System.out.println("新坐标(" + x2 + "," + y2 + ")");
}
}