如何返回到 Java 中的特定行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18604169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to go back to a specific line in Java?
提问by KTF
I'm writing code that involves an if-else statement asking the user if they want to continue. I have no idea how to do this in Java. Is there like a label I can use for this?
我正在编写包含 if-else 语句的代码,询问用户是否要继续。我不知道如何在 Java 中做到这一点。有没有我可以使用的标签?
This is kind of what I'm looking for:
这就是我正在寻找的东西:
--label of some sort--
System.out.println("Do you want to continue? Y/N");
if (answer=='Y')
{
goto suchandsuch;
}
else
{
System.out.println("Goodbye!");
}
Can anybody help?
有人可以帮忙吗?
回答by dasblinkenlight
Java has no goto
statement (although the goto
keyword is among the reserved words). The only way in Java to go back in code is using loops. When you wish to exit the loop, use break
; to go back to the loop's header, use continue
.
Java 没有goto
声明(尽管goto
关键字在保留字中)。在 Java 中返回代码的唯一方法是使用循环。当您希望退出循环时,请使用break
; 要返回循环的标题,请使用continue
.
while (true) {
// Do something useful here...
...
System.out.println("Do you want to continue? Y/N");
// Get input here.
if (answer=='Y') {
continue;
} else {
System.out.println("Goodbye!");
break;
}
}