4

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?

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?

4

1 回答 1

9

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;
    }
}
于 2013-09-04T01:47:06.110 回答