-----------android培訓、java培訓、java學習型技術博客、期待與您交流!------------
在此,分享一下自己學習JAVA的學習心得。有不對的地方請幫忙改正,也希望對想學java的同學有幫助!
JAVA語言基礎
程序流程控制
Java的控制結構分爲三部分:順序結構、選擇結構、循環結構。其中順序結構最爲簡單,不需要專門的java控制語句。
JAVA的控制語句主要有以下幾種:
(1)if語句和if-else語句;
(2)switch語句;
(3)for語句;
(4)while語句和do-while語句
(5)break語句和continue語句
選擇結構
(1)if-else語句格式:
if(布爾表達式)
語句1或語句塊1
else
語句2或語句塊2
注:if-else結構的簡寫格式:變量 = (條件表達式)?表達式1:表達式2;
Java代碼:
if-else語句練習代碼:
1.class IfDemo
2.{
3. public static void main(String[] args)
4. {
5. int x= 8;
6.
7. if(x<1 && x>12)
8. {
9. System.out.println("冬天");
10.
11. }
12.
13. else if(x>3 && x< 6)
14. {
15. System.out.println("夏天");
16.
17. }
18.
19. else if(x>6 && x< 9)
20. {
21. System.out.println("auter");
22.
23. }
24.
25. else if(x>10 && x< 12)
26. {
27. System.out.println("秋天");
28.
29. }
30.
31. else
32. {
33. System.out.println("春天");
34.
35. }
36. }
37.}
(2)switch語句
switch(表達式)
{
case 取值1:
執行語句;
break;
case 取值2:
執行語句;
break;
…...
default:
執行語句;
break;(可以省略)
}
循環結構
(1)for語句格式:
for(初始化表達式;循環條件表達式;循環後的操作表達式)
{
執行語句;
}
(2)while語句格式:
while(條件表達式)
{
執行語句;
}
do-while語句格式:
do
{
執行語句;
}while(條件表達式);
注 :1、do-while語句至少執行一次;
2、for語句與while語句區別:在有限次循環是選用for語句或者while語句,若是不知道循環次數最好選 用while語句。
3、三元運算符雖然可以簡化if else代碼。但是它是一個運算符,所以運算完必須要有一個結果。
Java代碼:
用for循環實現打印99乘法表:
1.class FunctionDemo
2.{
3.
4. public static void main (String args[])
5.
6. {
7. printer99();//打印99乘法表
8. }
9. public static void printer99()
10. {
11. for(int x=1; x<=9; x++)
12. {
13. for(int y=1; y<=x;y++)
14. {
15. System.out.print(x+"*"+y+"="+x*y+"\t");
16. }
17. System.out.println();
18. }
19. }
20.}
do-while循環練習代碼:1.class While
2.{
3. public static void main (String args[])
4. {
5. int x =1;
6.
7. do
8. {
9. x++;
10. System.out.println("x="+x);
11.
12. }
13. while(x<=10);
14. }
15.}
break語句和continue語句:
區別:1、break語句跳出所在循環體;而continue語句是結束本次循環,繼續下一次循環;
2、break語句可應用於選擇結構和循環結構;continue:只能作用於循環結構。
注:1、這兩個語句離開應用範圍,存在時沒有意義的。
2、這兩個語句單獨存在下面都不可以有語句,因爲執行不到。