使用switch時注意事項:
- 表達式類型只能是byte、short、int、char,JDK5開始支持枚舉,JDK7開始支持String,不支持double、float、long(精確度問題,小數有點不精確)。
- case給出的值不允許重復,且只能是字面量,不能是變量。
- 不要忘記寫break。
寫for循環的快捷鍵:fori+回車
ctrl+shift+Alt+j? 可以選中所有的和當前一樣的部分,然后一起修改
//生成隨機數,1-100之間(兩種方法)int num1 = (int)(Math.random()*100) + 1;Random r = new Random();int num2 = r.nextInt(100) + 1;
隨機數是前閉后開的,如何生成65-91之間的隨機數?
答:int number = r.nextInt(27)+65;//r.nextInt(27)是生成0-26之間的隨機數,加上65就是65-91之間了
小案例:隨機生成n
public static String getCode(int n){String code = "";for (int i = 0; i < n; i++) {int type = (int)(Math.random()*3);//0代表數字,1代表大寫字母,2代表小寫字母switch (type) {case 0:code += (int)(Math.random()*10);break;case 1:code += (char)(Math.random()*26+'A');break;case 2:code += (char)(Math.random()*26+'a');break;}}return code;}
靜態初始化數組:數據類型[ ]? 數組名 = {元素1,元素2,...}? ?例:int[ ]? arr = {12,24,36};
動態初始化數組:數據類型[ ]? 數組名 = new 數據類型[長度]? ?例:int[ ]? arr = new int[3];
數組名.fori +回車,快捷鍵可以快速寫出 for(int i = 0;i<nums.length;i++)
二維數組靜態:int[][] arr={{1,2,3},{4,5,6},{7,8,9}};
二維數組動態:int[][] arr = new int[3][5];