Java流程控制 的语法与 C/C++ 类似,也有 if…else、while、do…while、for、switch…case等,这里不再讲述具体语法,仅举例说明。
输出九九乘法表:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i+"*"+j+"="+j*i+" ");
}
System.out.print("\n");
}
}
}
运行结果:
println() 输出内容后换行,print() 不换行。
又如,求某一年的某一月有多少天:
import java.util.*;
public class Main {
public static void main(String[] args) {
int days = 0;
// 获取用户输入
Scanner sc = new Scanner(System.in);
System.out.print("输入年份:");
int year = sc.nextInt();
System.out.print("输入月份:");
int month = sc.nextInt();
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
// 判断闰年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
days = 29;
else
days = 28;
break;
default:
System.out.println("月份输入错误!");
System.exit(0); // 强制结束程序
}
System.out.printf("天数:%d\n", days);
}
}
运行结果:
输入年份:2019
输入月份:11
天数:30
Java中没有像C语言中的scanf()语句,从控制台获取输入有点麻烦,我推荐使用 Scanner 类,具体语法请大家自行查看API。
欢迎加入AIDE教程网官方交流群:961607042
版权声明:本文为AIDE教程网原创文章,转载请附上原文出处链接和本声明。
本文链接:https://www.aidemx.cn/1800.html
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持以下吧
请登录后发表评论
注册
社交帐号登录