1、switch語句
int a = 1,b =2; switch(a+b){ case 1: System.out.print(1); case 3: System.out.print(3); case 4: System.out.print(4); default: System.out.print(5); }
1、先執行 a b 得出值 3
2、找出對應case 3,然後繼續向下
3、執行執行所有的語句,因為沒有 break
線上免費影片教學推薦:java教學影片
##結果:345
int a = 2, b = 34; switch(a + b){ case 5: System.out.println(5); break; case 6: System.out.println(6); break; default: System.out.println(12); }1、執行 a b ,得出 36#2、執行 default結果:
12判斷月份
Scanner a = new Scanner(System.in); System.out.print("please input a month:"); int month = a.nextInt(); switch(month){ case 1: case 2: case 3: System.out.println("Spring"); break; case 4: case 5: case 6: System.out.println("Summer"); break; case 7: case 8: case 9: System.out.println("Autumn"); break; case 10: case 11: case 12: System.out.println("Winter"); break; default: System.out.println("fasle"); }
Scanner a = new Scanner(System.in); System.out.print("please input a month:"); int month = a.nextInt(); switch(month){ case 1: case 2: case 3: System.out.println("Spring"); break; case 4: case 5: case 6: System.out.println("Summer"); break; case 7: case 8: case 9: System.out.println("Autumn"); break; case 10: case 11: case 12: System.out.println("Winter"); break; default: System.out.println("fasle"); }兩個方式一樣,但switch語句內,的多個語句,即語句區塊,並不需要加花括號,因為碰到break語句跳出,否則繼續執行下去。 2、循環語句求1000以內的質數
int j; for (int i = 0; i < 1000; i++) { for (j = 2; j < i; j++) if (i % j == 0) break; if (j == i) System.out.println(i); }結果:
2 3 5 …當然上面犯了一個明顯的錯誤,最外層的循環應該是<=1000,雖然不影響什麼,但要記住。
for (int i = 0; i < 1000; i++) { if(i == 2) System.out.println(2); for (int j = 2; j < i; j++) { if(i % j == 0) break; if(j == i - 1 ) System.out.println(i); } }相關文章教學推薦:
以上是java學習之switch語句與循環語句的詳細內容。更多資訊請關注PHP中文網其他相關文章!