在开关案例中破裂

发布于 2025-02-13 00:06:11 字数 1488 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兮颜 2025-02-20 00:06:11

这不是break关键字工作的方式。它结束switch语句,而不是程序。

在您的代码中,如果该选项为,则代码将被执行,因为没有break> break 之前。

您可能想要这样的东西:

System.out.println("Do you want to continue ? (yes/no) ?");

String playAgain = scanner.nextLine();

switch (playAgain) {
case "yes":
  System.out.println("let's continue");
  break;

case "no":
  System.out.println("Bye");
  System.exit();

default:
  System.out.println("Please enter a right instruction");
  // You will need some control loop to make it work... 
}

That is not the way the break keyword works. It ends the switch statement, not the program.

In your code, if the option is yes, both yes and no codes will be executed because there is no break before the no.

You probably want something like that:

System.out.println("Do you want to continue ? (yes/no) ?");

String playAgain = scanner.nextLine();

switch (playAgain) {
case "yes":
  System.out.println("let's continue");
  break;

case "no":
  System.out.println("Bye");
  System.exit();

default:
  System.out.println("Please enter a right instruction");
  // You will need some control loop to make it work... 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文