java三种循环的区别_JavaSE三种循环注意点
while 和 do...while的區(qū)別:
當判斷條件表達式為false的時候, do...while會執(zhí)行一次do{}中的代碼。而while則直接跳過循環(huán)。
while 、do...while、for
break、continue:
break關(guān)鍵字:break 語句用于終止最近的封閉循環(huán)或它所在的 switch 語句。控制傳遞給終止語句后面的語句。
continue關(guān)鍵字:語句將控制權(quán)傳遞給它所在的封閉迭代語句的下一次迭代。(跳出本循環(huán),執(zhí)行下一次循環(huán))。
ps:return關(guān)鍵字:返回到方法調(diào)用處,執(zhí)行該方法的下方代碼。
死循環(huán):死循環(huán)同樣很重要,實際開發(fā)中,一般內(nèi)部都會設有在滿足一定需求下跳出循環(huán)的代碼。
Scanner的使用需注意問題
public class ScannerProblemDemo {
public static void main(String[] args) {
// 特殊情況:第一次獲取的是數(shù)字,第二次獲取是字符串
Scanner scan = new Scanner(System.in);
System.out.println("請輸入一個數(shù)字1");
int num1 = scan.nextInt();
System.out.println("請輸入一個字符串2");
scan.nextLine();
String str2 = scan.nextLine();
System.out.println(num1+","+str2);
/*
* 在控制臺輸入的所有數(shù)據(jù)都會進入內(nèi)存
* int num1 = scan.nextInt();
* num1會將內(nèi)存中的數(shù)據(jù)取走,但內(nèi)存中還保留了一個enter
* String str2 = scan.nextLine();str2直接就把上次留下的enter取走了
* 所以沒有給我們輸入字符串的機會
* 解決方式:先用scan.nextLine();把上次留下的enter取走
*/
}
}
當掃描器分別接收數(shù)字和字符串時,在輸出數(shù)字和字符串的中間插入 scan.nextLine();因為在控制臺輸入完數(shù)字或字符串時,需要按下回車鍵。此時,回車鍵的內(nèi)容會記錄到內(nèi)存中,因此插入scan.nextLine();來讀取出回車鍵對應的內(nèi)容。
冒泡排序、選擇排序
public class Demo{
public static void main(String args[]){
// 冒泡
int score [] = {7,2,8,3,9,1,0,12,65};
for(int i=1;i
for(int j=0;j
if(score[j]
int temp=0;
temp =score[j+1] ;
score[j+1] = score[j];
score[j] = temp;
}
}
}
}
//選擇
for(int i =0; i
for(int j =i+1; j
if(score[i]
int temp=0;
temp =score[j] ;
score[j] = score[i];
score[i] = temp;
}
}
}
總結(jié)
以上是生活随笔為你收集整理的java三种循环的区别_JavaSE三种循环注意点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java ee有哪些工具_JavaEE开
- 下一篇: java foreach order_J