做二手元器件那個網站查價格關鍵詞排名批量查詢軟件
1 編碼規(guī)范——衛(wèi)語句
??表達異常分支時,少用if-else方式。
??比如成績判斷中對于非法輸入的處理:
/*>=90 <=100 優(yōu)秀>=80 <90 良好>=70 <80 一般>=60 <70 及格<60 不及格*/@Testpublic void test2() {//int score = 78;//通過Scanner可以實現(xiàn)從控制臺輸入信息Scanner scanner = new Scanner(System.in);System.out.println("請輸入成績:");int score = scanner.nextInt();if(score < 0 || score > 100) {System.out.println("非法輸入");} else if (score >= 90 && score <= 100) {System.out.println("優(yōu)秀");} else if (score >= 80 && score < 90) {System.out.println("良好");} else if (score >= 70 && score < 80) {System.out.println("一般");} else if (score >= 60 && score < 70) {System.out.println("及格");} else {System.out.println("不及格");}}
??修改后:
@Testpublic void test2() {//通過Scanner可以實現(xiàn)從控制臺輸入信息Scanner scanner = new Scanner(System.in);System.out.println("請輸入成績:");int score = scanner.nextInt();//衛(wèi)語句1if (score < 0 || score > 0) {//異常和正常 要分開System.out.println("Invalid input!");//后面的代碼不再執(zhí)行return;}//衛(wèi)語句2...//合法輸入if (score >= 90 && score <= 100) {System.out.println("優(yōu)秀");} else if (score >= 80 && score < 90) {System.out.println("良好");} else if (score >= 70 && score < 80) {System.out.println("一般");} else if (score >= 60 && score < 70) {System.out.println("及格");} else {System.out.println("不及格");}}
2 循環(huán)控制語句(接Day2)
?2.2 continue、break
???還是跟C語法相差無幾,放個demo了事
???continue:跳出本次循環(huán),繼續(xù)下一次循環(huán)
???break:跳出離他最近的那層循環(huán)
@Test//結果: 1 2 4 5
public void test44() {for (int i = 1; i <= 5; i++) {if (i == 3) {continue;}System.out.println(i);}
}@Test//結果: 1 2
public void test45() {for (int i = 1; i <= 5; i++) {if (i == 3) {break;}System.out.println(i);}
}@Test//
public void test46() {//i,j,kfor (int i = 1; i <= 5; i++) {System.out.println("i: " + i);for (int j = 1; j <= 5; j++) {if (j == 3) {break;}System.out.println("j: " + j);}}
}
?2.3 雙重for循環(huán)
???這個也很簡單,
???雙重for循環(huán):
???外層循環(huán)控制行數,數一下有幾行就能確定外層循環(huán)。
???內層循環(huán)控制列數,這一行打印多少個,到底要打印多少個要找出和當前行之間的一個關系。
???還有一些打印金字塔, 各種三角形的題,統(tǒng)一放到下一篇作業(yè)博客吧.
?2.4 Switch
???這部分當初學的時候沒感覺有啥特別的,但是同種情況的case可以合并這個操作是真的有點沒記起來,溫故知新了。
import com.sdust.day2.*;@Test//月份 天數public void test2() {Scanner scanner = new Scanner(System.in);Homework day2 = new Homework();System.out.println("please input month: ");int month = scanner.nextInt();if (month < 1 || month > 12) {System.out.println("invalid month");return;}switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:System.out.println("31days");break;case 4:case 6:case 9:case 11:System.out.println("30days");break;case 2:System.out.println("please input year: ");int year = scanner.nextInt();if (day2.judgeLeapYear(year)) {System.out.println("29days");} else {System.out.println("28days");}default:System.out.println("default");break;}}
昨天寫了幾個作業(yè)題,包括一個閏年判斷的題,于是在今天寫這部分代碼對閏年進行特判的時候心血來潮想直接調用昨天的代碼。先是要導包,仿照Scanner輸入的形式寫了一下,發(fā)現(xiàn)還真行,嗯,基礎的Java也就那么回事嘛~