Java流程控制

  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(" ");

  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 ", days);

  41. }

  42. }

  运行结果:

  输入年份:2014

  输入月份:02

  天数:28

  Java中没有像C语言中的scanf()语句,从控制台获取输入有点麻烦,我推荐使用 Scanner 类,具体语法请大家自行查看API。(编辑:雷林鹏 来源:网络)

原文地址:https://www.cnblogs.com/pengpeng1208/p/9120884.html