下面的語句會編譯報錯或者打印什么?
System.out.print("baidu site :"); https://www.baidu.com; System.out.println(" format");
很多人會說:會編譯出錯,中間那行是什么鬼?
其實,不會報錯,會打印出:
baidu site : format
如果改成這樣的語句,是不是就不會覺得編譯報錯了?
System.out.print("baidu site :"); https : //www.baidu.com; System.out.println(" format");
像不像switch語句中的case
int q = (n+7)/8; switch (n%8) { case 0: do { foo(); // Great C hack, Tom, case 7: foo(); // but it's not valid here. case 6: foo(); case 5: foo(); case 4: foo(); case 3: foo(); case 2: foo(); case 1: foo(); } while (--q > 0); }
上面的語句,":" 是statement label 翻譯成標號語句。
其語法如下:
LabeledStatement: Identifier : Statement LabeledStatementNoShortIf: Identifier : StatementNoShortIf
與c和c++不同,JAVA中沒有goto語句;標號語句用于出現在標號語句內任何地方的break或者continue語句之上。
再來一個標句語句作為結尾的練習吧
class Test { char[] value; int offset, count; int indexOf(TestString str, int fromIndex) { char[] v1 = value, v2 = str.value; int max = offset + (count - str.count); int start = offset + ((fromIndex < 0) ? 0 : fromIndex); i: for (int i = start; i <= max; i++) { int n = str.count, j = i, k = str.offset; while (n-- != 0) { if (v1[j++] != v2[k++]) continue i; } return i - offset; } return -1; } }
參考資料
【1】https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.7