1. // 大家分析以下代码,编译器会报错吗?
    2. public class MethodTest07{
    3. public static void main(String[] args){
    4. // 调用方法
    5. int result = m();
    6. System.out.println(result)
    7. // 调用x方法
    8. int result1 = x(true);
    9. System.out.println("result1 = " + result1);
    10. // 再次调用x方法
    11. int result2 = x(false);
    12. System.out.println("result2 = " + result2);
    13. }
    14. //错误:缺少返回语句
    15. /*
    16. public static int m(){
    17. boolean flag = true; //编译器不负责运行程序,编译器只讲道理。
    18. // 对于编译器来说,编译器只知道flag变量是boolean类型
    19. // 编译器会认为flag有可能是false,有可能是true
    20. if(flag){
    21. // 编译器觉得:以下这行代码可能会执行,当然也可能不会执行
    22. // 编译器为了确保程序不出现任何异常,所以编译器说:缺少返回语句。
    23. return 1;
    24. }
    25. }
    26. */
    27. // 怎么修改这个程序
    28. // 第一种方案:带有else分支的可以保证一定会有一个分支执行。
    29. /*
    30. public static int m(){
    31. boolean flag = true;
    32. if(flag){
    33. return 1;
    34. }else{
    35. return 0;
    36. }
    37. }
    38. */
    39. // 第二种方案:该方案实际上是方案1的变形。
    40. // return语句一旦执行,所在的方法就会结束。
    41. /*
    42. public static int m(){
    43. boolean flag = true;
    44. if(flag){
    45. return 1;
    46. }
    47. return 0;
    48. }
    49. */
    50. /*
    51. // 在同一个域当中,"return语句"下面不能再编写其他代码。编写之后编译报错。
    52. public static int m(){
    53. boolean flag = true;
    54. if(flag){
    55. return 1;
    56. //错误:无法访问的语句
    57. //System.out.println("hello1");
    58. }
    59. // 这行代码和上面的代码hello1的区别是:不在同一个域当中。
    60. //System.out.println("hello2");
    61. return 0;
    62. // 错误:无法访问的语句
    63. //System.out.println("hello2");
    64. }
    65. */
    66. // 三目运算符有的时候会让代码很简练。
    67. public static int m(){
    68. boolean flag = true;
    69. return flag ? 1 : 0;
    70. }
    71. // 带有一个参数的方法。
    72. public static int x(boolean flag){
    73. return flag ? 1 : 0;
    74. }
    75. }