語法結構
語法結構分為(流程控制)
順序結構
是按照代碼的先后順序加載的
分支結構
單分支if
if(值){
代碼1;
}else{
代碼2;
}
if是判斷語句,返回的是Boolean(true/false)
多分支switch
switch(值){
case 值1:
代碼1;
[break;] (可有可無的)
case 值2:
代碼2;
case 值3:
代碼3;
default:
代碼4;
};
只能比較==的
小括號里的值是整點類型的(int short byte char)
if的好處(可以寫復雜的邏輯)壞處(執行的比較慢)
switch好處(判斷的效率更高) 壞處(只能做==(固定的))
附加:代碼規范
1.可讀性(起名字要規范,代碼縮進,多加注釋)
2.健壯性(程序嚴謹 )
lib提供好的類庫,Scanner應用類型
寫法:Scanner scanner = new Scanner(System.in);
int i = input.nextInt();
可以在控制面板上面操作。可讀取我們輸入的文字。 input.nextInt()讀取的字符串。
隨機數:Math.random();
package com.swy.game;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
//1.隨即搖色子的過程 隨機產生一個骰子點數 1-6整數
double value = Math.random();//doubled的取值范圍[0.0-1.0)
int num = (int)(value*6+1);
//2.讓玩家猜大小
Scanner input = new Scanner(System.in);
System.out.println("買定離手");
String choose = input.nextLine();//幫我們讀取輸入的文字
//3.比較點數與猜測結果
System.out.println("本次搖出的點數為:"+num);
if ((num <= 3 && choose.equals("小")) || (num >3 && choose.equals("大"))){
System.out.println("恭喜你 猜對了");
}else {
System.out.println("對不起 猜錯了");
}
}
}
循環結構
重復不停的做同樣的事情
for while do……while
for循環:
程序中想要執行一個正常的循環 需要滿足3個必要條件
1.初始值 2.終點判定條件 3.變化量
for( 初始值 ; 終點判定條件 ; 變化量){
好多好多代碼;
}
package com.swy.game;
//通過循環找尋三位數字的水仙花數;
public class Flowers {
public static void main(String[] args) {
for (int num = 100; num < 1000; num++) {
if (Math.pow(num/100, 3) + Math.pow(num%100/10,3) + Math.pow(num%10,3) == num){
System.out.println(num+"是水仙花數");
}
}
}
}
循環嵌套
在控制台輸出:”* * * *“
“* * * *”
“* * * *”
“* * * *”
package com.swy.game;
public class Star {
public static void main(String[] args) {
int count = 4;
for (int i = 0; i <= 4; i++) {
for (int j = 0; j < count; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
在控制台輸出:*
**
***
package com.swy.game;
public class StarTow {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
兩個重要的關鍵字
break(終止 終斷)
cotinue(終斷本次循環 執行下一行循環)
兩個循環的結構
while循環
初始值;
while(終點判斷條件){ //()里只能有一個
好多好多執行;
變化量;
}
do...while循環
初始值;
do{
好多好多執行;
變化量;
}while(終點判定條件){
}
while先判斷后執行 條件不滿足不執行
do...while先執行后判斷 條件不滿足 至少執行一次
package lianxi1;
public class ShuZu1 {
public static void main(String[] args) {
//冒泡排序----升序排序
int[] array = new int[]{5,4,3,2,1};
//循環
for (int i = 1; i < array.length; i++) {//控制執行的輪次
for (int j = array.length-1; j>=i; j--) {//控制比較次數
//判斷
if (array[j] < array[j-1]) {
int max = array[j];
array[j] = array[j-1];
array[j-1] = max;
}
}
}
for(int v : array ) {
System.out.println(v);
}
}
}