黑马程序员--Java基础学习第三天

一、流程控制结构

1、 顺序结构

2、 分支结构

3、 循环结构

二、语句

1、 赋值语句

2、 空语句

3、 复合语句(compound statement)

复合语句由一对{}括起来的语句序列组成的一条复合语句,在语法上作为一条语句使用,也成为块(block),其中可声明变量,这些变量的作用域仅限于当期复合语句。复合语句的格式如下:

{

[变量声明或常量声明];

语句序列;

}

4、 选择语句

(1)    if语句

练习:判断一个年份是否为闰年。

    public static boolean isLeapYear(int year)

{

boolean leap=year%400==0||year%100!=0&&year%4==0;

return leap;

}

 

(2)switch语句

5、 循环语句

(1)    while语句

(2)    do-while语句

(3)    for语句

l  练习一:获取1~10的和,并打印。

    public static int compute(int m,int n)

{

//使用while

int count=0;

while(m<=n)

{

count+=m;

m++;

}

return count;

}
    public static int compute_2(int m,int n)

{

//使用for

int count=0;

for(;m<=n;m++)

{

count+=m;

}

return count;

}

 

l  练习二:1~100之间7的倍数的个数。并打印。

    public static int count(int m,int n,int x)

{

int count=0;

while(m<=n)

{

if(m%x==0)

{

count++;

System.out.println(m);

}

m++;

}

return count;

}

 

l  练习三:for嵌套,打印:

    public static void print()

{

for(int i=0;i<5;i++)

{

for(int j=i;j<5;j++)

{

System.out.print('*');

}

System.out.println();

}



for(int i=0;i<5;i++)

{

for(int j=5-i-1;j<5;j++)

{

System.out.print('*');

}

System.out.println();

}

}

 

l  练习四:打印:

1

12

123

1234

12345

    public static void print()

{

for(int i=0;i<5;i++)

{

for(int j=0;j<=i;j++)

{

System.out.print(j+1);

}

System.out.println();

}

}

 

l  练习五:for嵌套,九九乘法表。

    public static void print()

{

for(int i=1;i<10;i++)

{

for(int j=1;j<=i;j++)

{

System.out.print(j+"*"+i+"="+j*i+"\t");

}

System.out.println();

}

}

 

6、 转移语句

(1)    return语句

return语句使程序从方法中返回到方法调用处,并为方法返回一个值。return语句的语法格式是:

return[返回值];

(2)    break语句和continue语句

break语句用于switch语句的case子句和循环体中,作用是跳出循环体,终止循环。

continue语句用于循环体中,作用是跳出本次循环,执行下一循环。

三、方法(function)

1、 方法声明

2、 方法调用

3、 方法重载(overload)

一个类中如果有多个同名方法但带有不同的参数列表,称为方法的重载。重载方法的参数列表不同是指参数的数据类型或个数或次序不同。

4、 递归方法

存在直接或间接调用自身的算法称为递归算法()。递归定义的问题可用递归算法求解,按照递归定义将问题简化,逐步递推,直到获得一个确定值。

递归定义必须满足一下两个条件:

(1)    边界条件——至少有一条初始定义是非递归的。

(2)    递归通式——由已知函数值逐步递推计算出未知函数值。

练习一:求n!的递归方法。

    public static int factorial(int n)

{

if(n>=0)

{

if(n==0||n==1)

return 1;

else

return n*factorial(n-1);

}

return -1;

}

 

练习二:求Fibonacci数列第n项的递归方法。

    public static int fibonacci(int n)

{

if(n>=0)

{

if(n==0||n==1)

{

return n;

}

else

return fibonacci(n-2)+fibonacci(n-1);

}

return -1;

}

 

posted on 2012-03-20 10:03  黑马程序员  阅读(307)  评论(0)    收藏  举报

导航