是否有任何語法允許您從一行跳轉到另一行?Java中的跳線?
例如:
System.out.println("line");
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
//goto line2 or something like that??
是否有任何語法允許您從一行跳轉到另一行?Java中的跳線?
例如:
System.out.println("line");
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
//goto line2 or something like that??
沒有,沒有goto
說法,但有幾個解決方法:
do {
//do stuff
if (condition) break; //this will jump--+
//do stuff // |
} while (false); // |
// here <-----------------------------------+
和
int id = 0;
while (true) {
switch (id) {
case 0:
//do stuff
if (condition) {id = 3; break;} //jumps to case 3:
case 1:
if (condition) {id = 1; break;} //jumps to case 1:
// ...
}
}
沒有在Java中沒有goto雖然它是一個保留關鍵字。
goto被認爲是一個糟糕的編程結構,因此被排除在Java之外。
你可以以一種迂迴的方式與switch語句實現這一點,例如:
switch (lineNum) {
case 1: System.out.println("line 1");
case 2: System.out.println("line 2");
case 3: System.out.println("line 3");
case 4: System.out.println("line 4");
}
現在,你必須確保lineNum
有適當的值。
對於任何向後跳躍,您需要一個do
或while
循環。
即可調用它們Marko巧妙地利用java開關的後續功能;例如如果lineNum = 2,那麼情況2,3,4都會運行。 – Bathsheba
你想達到什麼目的?你可以使用標籤是http://geekycoder.wordpress.com/2008/06/25/tipjava-using-block-label-as-goto/,反正使用goto語句就像語句可能會導致意大利麪條代碼
Java 故意不支持轉到。這是爲了鼓勵(強制)使用適當的條件結構來構建控制流。
在你的榜樣,正確的方法是一個while循環:
System.out.println("line");
while (true) {
System.out.println("line2");
System.out.println("line3");
System.out.println("line4");
}
如果你想想看,沒有不能無需跳轉來表達碼流模式(它可能需要偏離個人根深蒂固的習慣)。您只有可能想要使用goto是爲了避免代碼重複。如果遇到這種情況,可以將代碼重新組合爲一個可以在需要時調用的單獨方法,這是一種更簡潔的解決方案。
您可以創建方法,每個方法都包含一行,並且只要您想模擬'goto' –