三种基本控制流程结构
顺序结构
分支结构
- if-else结构
面试题:
@Test
public void test2() {
boolean b = true;
//如果写成if(b=false)能编译通过吗?如果能,结果是?
if(b == false) System.out.println("a");
else if(b) System.out.println("b");
else if(!b) System.out.println("c");
else System.out.println("d");
}
如果写成if(b=false)能编译通过吗?如果能,结果是c
- switch-case结构
public static void whichDay(){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scanner.nextInt();
System.out.println("请输入月份:");
int month = scanner.nextInt();
System.out.println("请输入日期:");
int day = scanner.nextInt();
boolean isRun = false;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
isRun = true;
}
int days = 0;
switch (month){
case 12:
days += 30;
case 11:
days += 31;
case 10:
days += 30;
case 9:
days += 31;
case 8:
days += 30;
case 7:
days += 31;
case 6:
days += 30;
case 5:
days += 31;
case 4:
days += 30;
case 3:
days += 31;
case 2:
if (isRun) days += 29;
else days += 28;
case 1:
days += day;
}
System.out.println(year+"年"+month+"月"+day+"日为"+year+"年的第"+days+"天");
}
循环结构
- for循环
练习:输入两个正整数 m 和 n ,求其最大公约数和最小公倍数
public static void test1(){
System.out.println("请输入正整数 m 和 n:");
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
int minVal = (m < n ? m : n);
int maxVal = (m > n ? m : n);
int i, j;
for (i = minVal; i > 0; i--) {
if (m % i == 0 && n % i == 0) {
break;
}
}
for (j = maxVal; ; j++) {
if (j % m == 0 && j % n == 0) {
break;
}
}
System.out.println("最大公约数为:" + i + ",最小公倍数为" + j);
}
练习:输出所有的水仙花数,所谓水仙花数是指一 个 3 位数 ,其各个位上数
字立方和等于其本身。
public static void test2(){
int i, j, k;
for (int num = 100; num < 1000; num++) {
i = num / 100;
j = num / 10 % 10;
k = num % 10;
if (Math.pow(i, 3) + Math.pow(j, 3) + Math.pow(k, 3) == num) {
System.out.println(num);
}
}
}
-
while循环
-
do-while循环
-
嵌套循环
特殊关键字的使用——break、continue
经典面试题
写出输出结果:
class Demo{
public static void main(String[] args){
int a=3,b=8;
int c=(a>b)?a++:b++;
System.out.println("a="+a+"\tb="+b+"\tc="+c); //
int d=(a>b)?++a:++b;
System.out.println("a="+a+"\tb="+b+"\td="+d); //
int e=(a<b)?a++:b++;
System.out.println("a="+a+"\tb="+b+"\te="+e); //
int f=(a<b)?++a:++b;
System.out.println("a="+a+"\tb="+b+"\tf="+f); //
}
}
Ans: