回顧
一矛绘、循環(huán)的跳轉(zhuǎn)
1.break語句
①不帶標(biāo)簽的break
②帶標(biāo)簽的break
2.continue語句
①不帶標(biāo)簽的continue
②帶標(biāo)簽的continue
學(xué)習(xí)小結(jié)
一陡叠、循環(huán)的跳轉(zhuǎn)
3.return語句
離開return語句所在的方法吱窝,可以返回一個值攻人。
語法格式:
return;
reture 返回值;
注:
1.三元運算相當(dāng)于if...else語句颈走,只有在if...else語句的主體部分很少時才使用敞峭;
2.switch中并不是每一個case都需要break語句;
3.三種循環(huán)可以互相轉(zhuǎn)換球订;
4.循環(huán)中通常使用半開區(qū)間后裸,提高了可讀性,即for(int i = 0;i < 10;++i)冒滩,而非for(int i = 0;i <= 10;++i)
實戰(zhàn)習(xí)題
1.使用循環(huán)控制語句計算“1+2+...+100”的值:
public class P164_7_6_1 {
public static void main(String[] args) {
int sum = 0; // 初始化sum和變量
for (int i = 1; i <= 100; i++) {
sum += i; // 循環(huán)累加100次
}
System.out.println("1+2+...+100 = " + sum); // 輸出計算值
}
}
2.隨機(jī)產(chǎn)生1~12的某一個數(shù)微驶,輸出相應(yīng)月份的天數(shù)(2月算28天):
public class P164_7_6_2 {
public static void main(String[] args) {
double rand = Math.random(); // 隨機(jī)產(chǎn)生[0,1)的一個double數(shù)
int month = 1 + (int)(12 * rand); // 處理為1~12的隨機(jī)數(shù)
switch (month) { // 相應(yīng)月份并輸出
case 1:
System.out.println(month + "月共有31天");
break;
case 2:
System.out.println(month + "月共有28天");
break;
case 3:
System.out.println(month + "月共有31天");
break;
case 4:
System.out.println(month + "月共有30天");
break;
case 5:
System.out.println(month + "月共有31天");
break;
case 6:
System.out.println(month + "月共有30天");
break;
case 7:
System.out.println(month + "月共有31天");
break;
case 8:
System.out.println(month + "月共有31天");
break;
case 9:
System.out.println(month + "月共有30天");
break;
case 10:
System.out.println(month + "月共有31天");
break;
case 11:
System.out.println(month + "月共有30天");
break;
case 12:
System.out.println(month + "月共有31天");
break;
default:
System.out.println("程序出錯!");
break;
}
}
}
3.判斷某年是否為閏年:
public class P164_7_6_3 {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in); // 實例化一個掃描Scanner類
System.out.println("請輸入4位數(shù)的年份:");
int year = scan.nextInt(); // 獲取輸入的年份
if(year % 4 == 0){ // 判斷是否被4整除
System.out.println(year + "年是閏年开睡!");
}else{
System.out.println(year + "年不是閏年因苹!");
}
}
}
思考
真是慚愧,昨天沒有學(xué)習(xí)篇恒。直接睡著了扶檐,睡著了,睡著了......這些天胁艰,每天都要外出工作款筑,都是一整天,加上舟車勞頓腾么,確實有些累醋虏,我感覺基礎(chǔ)又扎實了一些,昨天的進(jìn)度還是要追的哮翘,明天學(xué)習(xí)數(shù)組颈嚼。造起來!
記于2017年6月28日夜(29日凌晨)