Day 5
今天学习while,do-while循环并进行生成当月日历的程序编写。
1.while
while实际上就是把for循环展开
for(表达式1;表达式2;表达式3){
循环体;
}
---------------------------------------------------------------
表达式1;
while(表达式2){
循环体;
表达式3
}
while与for在使用方面的选择:
循环次数是确定的,优先选择for循环
循环次数不确定,优先选择while循环
2.do-while:
语法:
表达式1;
do{
循环体;
表达式3:
}while(表达式2);
执行流程:
首先执行表达式1
直接执行循环体,然后执行表达式2,根据表达式2的结果,决定是否再次循环
while和do-while的区别
while:先判断,后执行
do-while:先执行,后判断
例:计算一个任意位的正整数的各个位置上的数字之和
public class While {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
int num = input.nextInt();
do {
int a = num % 10;
sum += a;
num /= 10;
} while (num > 0);
System.out.println(sum);
}
}
3.关于日历的编写
从键盘输入年份和月份,在控制台产生本月的月历(第一行显示周几,下面的行对应的是号数),
周一是从1900年1月1号开始的效果如下:
代码如下:
public static void main(String[] args) {
/*
* 从键盘输入年份和月份,在控制台产生本月的月历 (第一行显示周几,下面的行对应的是号数), 周一是从1900年1月1号开始的
*
*
*/
Scanner input = new Scanner(System.in);
System.out.print("请输入年份:");
int year = input.nextInt();
if (year < 1900) {
System.out.println("输入错误!");
input.close();
return;
}
System.out.print("请输入月份:");
int mouth = input.nextInt();
if (mouth < 1 || mouth > 12) {
System.out.println("输入错误!");
input.close();
return;
}
int day;
System.out.print("日\t");
System.out.print("一\t");
System.out.print("二\t");
System.out.print("三\t");
System.out.print("四\t");
System.out.print("五\t");
System.out.println("六\t");
int sum = 0;
// 判断闰平年求天数
if (mouth == 4 || mouth == 6 || mouth == 9 || mouth == 11) {
day = 30;
} else if (mouth == 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
day = 29;
} else {
day = 28;
}
} else {
day = 31;
}
// 计算输入年份前的天数
for (int i = 1900; i < year; i++) {
if ((i % 4 == 0 && i % 100 != 0) || (i % 400 == 0)) {
sum += 366;
} else {
sum += 365;
}
}
// 计算输入月份前当年的天数
for (int j = 1; j < mouth; j++) {
if (j == 4 || j == 6 || j == 9 || j == 11) {
sum += 30;
} else if (j == 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
sum += 29;
} else {
sum += 28;
}
} else {
sum += 31;
}
}
// 计算这个月第一天是周几
int a = sum % 7 + 1;
// 输出月历
// 输出空格
if (a != 7) {
for (int k = 0; k < a; k++) {
System.out.print("\t");
}
}
// 输出日期
int count = 1;
do {
switch (a) {
case 7:
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.print(count + "\t");
break;
case 6:
System.out.println(count + "\t");
break;
}
a++;
if (a > 7) {
a = 1;
}
count++;
if (count > day) {
input.close();
return;
}
} while (true);
}
把之前学的都用一下用了一下。
关于\t
开始想要对齐日历的输出结果我使用了空格,但是发现两位数和一位数的混杂让空格不好确定,于是我查了一下,发现\t这个符号。
\t是补全当前字符串长度到8的整数倍,最少1个最多8个空格。
补多少要看你\t前字符串长度:
比如当前字符串长度6,那么\t后长度是8,也就是补2个空格
比如当前字符串长度10,那么\t后长度是16,也就是补6个空格
如果当前字符串长度12,此时\t后长度是16,补4个空格