Re: [問題] 面試遇到的JAVA問題

看板java作者 (LaPass)時間14年前 (2011/11/12 21:49), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)

11/12 11:05,
有沒有什麼範例可顯示出原例與x,y在同一區塊中初始化的差別
11/12 11:05
public class Test { public static void main(String[] args) { int a = 1; { int b = 2; System.out.println(a); //OK } //System.out.println(b); //編譯錯誤 Lable1:{ if(a==1) break Lable1; //跳離區塊 } } } 很多程式語言都能夠直接打個未標記的{}而不會出現錯誤 在JAVA中,我覺得有需要直接給括弧的狀況,也只有給他一個標籤(Lable) 然後用break直接跳離那個區塊而已 離開括弧,在括弧中宣告的變數會被註銷,但這也沒什麼用途 我實在搞不懂直接用括弧刮起來能幹什麼 像範例那個,好像完全沒必要 ※ 引述《qrtt1 (我要越級挑戰)》之銘言: : ※ 引述《wemee (我不為讀者改變作風)》之銘言: : : 有一些題目 類似以下用法 : : 但我完全不知道這麼用的意義是什麼 : : 例如 : : class Foo : : { : : { : : x = 1; : : { : : y = 2; : : } : : } : : int x, y; : : } : : 分成區塊中的區塊 有什麼意義嗎? : : 通常不是這麼寫就好了 : : { : : x = 1; : : y = 2; : : } : : 難道只是要先嚇嚇人而已 : 寫個小例子跑看看唄。 : public class Init { : static { : System.out.println("class init."); : } : { : System.out.println("instance init. 1"); : x = 1; : { : System.out.println("instance init. 2"); : y = 2; : } : } : int x, y; : public Init() { : System.out.println("ctor"); : } : { : System.out.println("instance init. 3"); : } : public static void main(String[] args) { : new Init(); : } : } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 125.233.155.87
文章代碼(AID): #1EldbSRB (java)
文章代碼(AID): #1EldbSRB (java)