Java流程式控制制

來源:互聯網
上載者:User

標籤:14.   amp   空格   util   文法   static   流程式控制制   dem   擷取   

  Java流程式控制制的文法與 C/C++ 類似,也有 if...else、while、do...while、for、switch...case等,這裡不再講述具體文法,僅舉例說明。

  輸出九九乘法表(右上三角):

  1. public class Demo {

  2. public static void main(String[] args){

  3. int i, j;

  4. for(i=1; i<=9; i++){

  5. for(j=1; j<=9; j++){

  6. if(j<i){< p="">

  7. //列印八個空格,去掉空格就是左上三角形

  8. System.out.print(" ");

  9. }else{

  10. System.out.printf("%d*%d=%2d ", i, j, i*j);

  11. }

  12. }

  13. System.out.print("\n");

  14. }

  15. }

  16. }

  運行結果:

  1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9

  2*2= 4 2*3= 6 2*4= 8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18

  3*3= 9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27

  4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36

  5*5=25 5*6=30 5*7=35 5*8=40 5*9=45

  6*6=36 6*7=42 6*8=48 6*9=54

  7*7=49 7*8=56 7*9=63

  8*8=64 8*9=72

  9*9=81

  Java中也有 printf() 語句,用來控制輸出格式,不過實際開發中不常用,因為輸出到控制台的資料很少要求嚴格的格式,一般 println() 和 print() 就夠了。

  println() 輸出內容後換行,print() 不換行。

  又如,求某一年的某一月有多少天:

  1. import java.util.*;

  2. public class Demo {

  3. public static void main(String[] args){

  4. int days = 0;

  5.

  6. // 擷取使用者輸入

  7. Scanner sc = new Scanner(System.in);

  8. System.out.print("輸入年份:");

  9. int year = sc.nextInt();

  10. System.out.print("輸入月份:");

  11. int month = sc.nextInt();

  12.

  13. switch(month){

  14. case 1:

  15. case 3:

  16. case 5:

  17. case 7:

  18. case 8:

  19. case 10:

  20. case 12:

  21. days=31;

  22. break;

  23. case 4:

  24. case 6:

  25. case 9:

  26. case 11:

  27. days=30;

  28. break;

  29. case 2:

  30. // 判斷閏年

  31. if(year%4==0 && year%100!=0 || year%400==0)

  32. days=29;

  33. else

  34. days=28;

  35. break;

  36. default:

  37. System.out.println("月份輸入錯誤!");

  38. System.exit(0); // 強制結束程式

  39. }

  40. System.out.printf("天數:%d\n", days);

  41. }

  42. }

  運行結果:

  輸入年份:2014

  輸入月份:02

  天數:28

  Java中沒有像C語言中的scanf()語句,從控制台擷取輸入有點麻煩,我推薦使用 Scanner 類,具體文法請大家自行查看API。(編輯:雷林鵬 來源:網路)

Java流程式控制制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.