1. switch
-
在Java中,switch中的变量类型可以是 byte、short、int、char、String(从Java SE 7支持)
-
case 标签必须为字符串常量或和字面量
例:
public static void main(String[] args) {
String str = "Hello World";
switch (str){
case "Hello":
System.out.println("Hello");
break;
case "World":
System.out.println("World");
break;
case "Hello World":
System.out.println("Hello World");
break;
default:
System.out.println("NULLL");
break;
}
}
反编译.class文件(利用Idea):
首先将编译生成的.class文件拷贝到对应的.java文件目录下:
(其中.class文件在out文件夹下)
在Idea中直接双击该.class,打开的便是反编译后的文件
若出现该窗口点击同意,为同意使用该反编译器
反编译代码:
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package Kuang.Struct; public class SwitchDemo { public SwitchDemo() { } public static void main(String[] args) { String str = "Hello World"; byte var3 = -1; switch(str.hashCode()) { case -862545276: if (str.equals("Hello World")) { var3 = 2; } break; case 69609650: if (str.equals("Hello")) { var3 = 0; } break; case 83766130: if (str.equals("World")) { var3 = 1; } } switch(var3) { case 0: System.out.println("Hello"); break; case 1: System.out.println("World"); case 2: System.out.println("Hello World"); break; default: System.out.println("NULLL"); } } }
- case语句后面可不加
break语句
,如果没有break 语句
出现,程序会继续执行下一条case 语句
,直到出现 break 语句。
例:通过switch语句计算某一天是当年的第多少天
public static void main(String[] args) {
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();
scanner.close();
System.out.println(year+"-"+month+"-"+day+"为当年第"+dayOfYear(year,month,day)+"天");
}
//是否是闰年
public static boolean isLeapYear(int year){
return ( year%400==0 || ( year%4==0 && year%100!=0 ) );
}
//某个日期是当年的多少天
public static int dayOfYear(int year,int month,int day){
int days = day;
switch (month){
case 12:
days += 30;
case 11:
days += 31;
case 10:
days += 30;
case 9:
days += 31;
case 8:
days += 31;
case 7:
days += 30;
case 6:
days += 31;
case 5:
days += 30;
case 4:
days += 31;
case 3:
if(isLeapYear(year))
days += 29;
else
days += 28;
case 2:
days += 31;
}
return days;
}
2.for
- for循环break或者continue多层循环:加上
标签
,使用break /continue 标签;
语句退出/继续标签
位置处的循环 - Java中无goto语句
例:
public static void main(String[] args) {
//设置标号Lable
Lable:for(int i=0;i<10;i++){
for(int j=0;j<5;j++){
System.out.print(i+" "+j + ",");
if(i == 2 && j == 4)
break Lable;
}
System.out.println();
}
}
- 增强for循环(即foreach)
格式:
for(声明语句 : 表达式)
{
//代码句子
}
例:
public static void main(String[] args) {
String[] cities = new String[]{"北京","重庆","长沙","南京"};
for(String city : cities){
System.out.println(city);
}
}