1.if else 的一般嵌套规则
在使用if else 嵌套的时候,一般为三到四层,不宜过多。
2.switch语句的一个实例
package com.lwj.basic;
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请你输入你要查询的数字,我们会为您查询对应的季节:");
int season = sc.nextInt();
switch(season){
case 1:
System.out.println("春季,出去浪吧!");
break;
case 2:
System.out.println("夏季,太热啦,学校还不给装空调!");
break;
case 3:
System.out.println("秋季,捡树叶去吧,银杏叶很美!");
break;
case 4:
System.out.println("冬季,买羽绒服了吗?");
break;
default:
System.out.println("怀疑你是火星来的,地球没有对应的第"+season+"个季节!");
}
}
}
结果:
请你输入你要查询的数字,我们会为您查询对应的季节:
5
怀疑你是火星来的,地球没有对应的第5个季节!
Process finished with exit code 0
Switch 的一些注意事项
Switch的变量类型可以是byte、short、int、long、char,从jdk1.7开始,我们也可以用String类型,但需要注意的是case标签必须为字符串常量或者是字面量;Switch可以有多个case语句,每一case语句跟一个比较的值和一个冒号;遇到break才会跳出语句;switch可以有default。但必须是最后的分支,default可以有break,但因为它代表的最后的,没有意义
3.for循环的实例
package com.lwj.basic;
public class For {
public static void main(String[] args) {
int sum = 0;
for(int i=1; i<=100; i++){
if(i%2==0){
sum+=i;
}
}
System.out.println("1-100的偶数和:"+sum);
}
}
1-100的偶数和:2550
Process finished with exit code 0
4.求“水仙花数”
什么是水仙花数:水仙花数就是如同153这样的数
1的立方+5的立方+3的立方=1+125+27=153
着重掌握代码中如何求一个数的个十百位数
package com.lwj.basic;
public class Fortest {
public static void main(String[] args) {
for(int i=100; i<=999; i++){
//1求出百位数
int bw = i / 100;
//求出十位数
int sw = i % 100 / 10;
//求出个位数
int gw = i % 10;
//求和
int sum = bw*bw*bw+sw*sw*sw+gw*gw*gw;
//判断
if(sum == i){
System.out.println(i);
}
}
}
}
153
370
371
407
Process finished with exit code 0
5.while循环
while语句的格式:
package com.lwj.basic;
public class While {
/*
输出1-10数字
*/
public static void main(String[] args) {
// for循环解决
for (int i=1; i<=10; i++){
System.out.println(i);
}
// while循环解决
int i = 1;
while(i<=10){
System.out.println(i);
i++;
}
/*类比发现for和while循环的规律*/
}
}
i的值是11