在Java中使用switch,但不确定为什么它起作用。

huangapple go评论104阅读模式
英文:

Using switch in Java but not sure why it works

问题

我尝试实现一个选项,当我的程序启动时,可以选择进入管理员界面或商店前台界面。当我在程序开始时添加了使用开关和情况,它立即起作用,但我不知道为什么。当我输入选项2进入商店前台时,它进入了,我以为我需要创建一个方法让它进入商店前台。

有人能解释一下我的代码开头到底发生了什么吗?我认为我只是碰巧幸运。

  1. public static void main(String[] args) throws IOException {
  2. while (true) {
  3. System.out.println("登录到管理员站点(1)或进入商店前台(2)?");
  4. int choice = scnr.nextInt();
  5. switch (choice) {
  6. case 1:
  7. StoreFront server = new StoreFront(0);
  8. server.start(6666);
  9. break; // 添加这行以确保仅在选择1时执行
  10. case 2:
  11. // 这里可以添加进入商店前台的代码
  12. break;
  13. }
  14. inventoryManager.initializeInventoryFromFile("inventory.json");
  15. System.out.println("欢迎来到游戏商店\n");
  16. System.out.println("请从菜单中选择一个选项");
  17. System.out.println("***************************************");
  18. System.out.println("************主菜单 ******************\n");
  19. while (true) {
  20. System.out.println("输入以下选项之一:\n\n" + "'1' : 查看产品\n" + "'2' : 购买产品\n"
  21. + "'3' : 退还产品\n" + "'4' : 退出");
  22. int menuChoice = scnr.nextInt();
  23. switch (menuChoice) {
  24. case 1:
  25. viewProducts();
  26. break;
  27. case 2:
  28. purchaseProducts();
  29. break;
  30. case 3:
  31. returnProducts();
  32. break;
  33. case 4:
  34. System.out.println("感谢光临。请再次光临。");
  35. System.exit(0);
  36. break;
  37. default:
  38. System.out.println("无效选项。请选择选项1-4");
  39. scnr.close();
  40. }
  41. // server.cleanUp();
  42. }
  43. }
  44. }

请注意,我在选择1时添加了break;以确保仅在选择1时执行相关代码。这可能是你之前代码中缺少的部分,导致它在选择2时也执行了相关代码。

英文:

I was trying to implement an option when my program starts to either enter the admin side or the storefront side. When I added using switch and case at the start of my program it worked right away but I don't know why. When I enter option 2 to go to the store front it enters and I thought I would need to make a method for it to enter the store front.

Can someone explain what is exactly happening at the beginning of my code? I think I just happened to get lucky.

  1. public static void main(String[] args) throws IOException {
  2. while (true) {
  3. System.out.println("Login to Admin site (1) or go to store front (2)?");
  4. int choice = scnr.nextInt();
  5. switch (choice) {
  6. case 1:
  7. StoreFront server = new StoreFront(0);
  8. server.start(6666);
  9. case 2:
  10. }
  11. inventoryManager.initializeInventoryFromFile("inventory.json");
  12. System.out.println("Welcome to the Game Store \n");
  13. System.out.println("Please select an option from the menu");
  14. System.out.println("***************************************");
  15. System.out.println("************MAIN MENU ******************\n");
  16. while (true) {
  17. System.out.println("Enter one of the following:\n\n" + "'1' : View Products\n" + "'2' : Purchase Products\n"
  18. + "'3' : Return Products\n" + "'4' : Exit");
  19. int menuChoice = scnr.nextInt();
  20. switch (menuChoice) {
  21. case 1:
  22. viewProducts();
  23. break;
  24. case 2:
  25. purchaseProducts();
  26. break;
  27. case 3:
  28. returnProducts();
  29. break;
  30. case 4:
  31. System.out.println("Thank you for coming by. Please come again.");
  32. System.exit(0);
  33. break;
  34. default:
  35. System.out.println("INVALID OPTION. Please select an option 1-4");
  36. scnr.close();
  37. }
  38. // server.cleanUp();
  39. }
  40. }
  41. }
  42. }

答案1

得分: 0

当我输入选项2以进入商店前台时,它进入了,我以为我需要为其创建一个进入商店前台的方法。

没有运气,这就是switch结构的功能方式。

它是多个if-else语句的优化等价物。

以下两种结构在控制流方面是等价的。
注意break关键字。

  1. switch (choice) {
  2. case 1:
  3. StoreFront server = new StoreFront(0);
  4. server.start(6666);
  5. break;
  6. case 2:
  7. break;
  8. }
  9. if (choice == 1) {
  10. StoreFront server = new StoreFront(0);
  11. server.start(6666);
  12. } else if (choice == 2) {
  13. }

实际上,你的第二个分支,case 2,没有附加的语句,因此不执行任何操作,并且退出switch。

是否有更好的实现方式?我的方式会有“bug”吗?

它可能被视为“buggy”,因为分支不需要大括号,忘记添加break关键字可能会导致代码冲突。

这是一种非常古老的语法,抽象自C编程语言。
与标签类似,除非必要,Java建议避免使用。

以下是较新的switch结构的示例,其语法略有不同。

不使用冒号":",而是使用 "->"。并且,break被隐含。

  1. switch (choice) {
  2. case 1 -> {
  3. StoreFront server = new StoreFront(0);
  4. server.start(6666);
  5. }
  6. case 2 -> { }
  7. }
英文:

> "... When I enter option 2 to go to the store front it enters and I thought I would need to make a method for it to enter the store front. ..."
>
> "... Can someone explain what is exactly happening at the beginning of my code? I think I just happened to get lucky."

No luck, that's how the switch structure will function.

It's an optimized equivalent of multiple if-else statements.

The following two structures are equivalent, in terms of control flow.
Note the break keyword.

  1. switch (choice) {
  2. case 1:
  3. StoreFront server = new StoreFront(0);
  4. server.start(6666);
  5. break;
  6. case 2:
  7. break;
  8. }
  9. if (choice == 1) {
  10. StoreFront server = new StoreFront(0);
  11. server.start(6666);
  12. } else if (choice == 2) {
  13. }

Essentially, your second branch, case 2, has no attributing statements, so nothing is executed, and the switch is exited.

> "... is there a better way I could implement this? Would my way be "buggy" in a sense?"

It might be viewed as "buggy" since the branches don't require brackets, and forgetting to add the break keyword can cause the code to conflict.

It's a very old syntax, abstracted from the C programming language.
Similar to labels, which Java recommends to avoid unless necessary.

Here is an example of the newer switch structure, which has a slightly different syntax.

Instead of the colon, :, you use ->.  And, a break is inferred.

  1. switch (choice) {
  2. case 1 -> {
  3. StoreFront server = new StoreFront(0);
  4. server.start(6666);
  5. }
  6. case 2 -> { }
  7. }
  8. </details>
  9. # 答案2
  10. **得分**: 0
  11. 你的示例中唯一的问题是这一部分
  12. ```java
  13. switch (choice) {
  14. case 1:
  15. StoreFront server = new StoreFront(0);
  16. server.start(6666);
  17. case 2:
  18. }

在执行完 case 1 后,它会“穿透”到尚未定义的 case 2。除非你希望它们穿透,否则应在每个 case 后使用 break

上述代码等同于:

  1. if (choice == 1) {
  2. StoreFront server = new StoreFront(0);
  3. server.start(6666);
  4. }
  5. // 现在执行 case 2 应该做的事情

不要忘记 switch 表达式

  1. for (int choice : new int[]{2, 4}) {
  2. int result = switch (choice) {
  3. case 1, 2, 3 -> 5; // 对于 1、2 或 3 返回 5
  4. case 4, 5, 6 -> { // 对于 4、5 或 6 也是类似的
  5. System.out.println("返回 6");
  6. yield 6;
  7. }
  8. default -> 1;
  9. };
  10. System.out.println("result = " + result);
  11. }

打印结果为:

  1. result = 5
  2. 返回 6
  3. result = 6
英文:

The only problem with your example that I can see is this part:

  1. switch (choice) {
  2. case 1:
  3. StoreFront server = new StoreFront(0);
  4. server.start(6666);
  5. case 2:
  6. }

After case 1 is executed, it "falls thru" to case 2 (which has yet to be defined). You should use a break after each case unless you want them to fall thru.

The above is the equivalent of

  1. if(choice == 1) {
  2. StoreFront server = new StoreFront(0);
  3. server.start(6666);
  4. }
  5. // now execute what case 2 would do

And don't forget the switch expression

  1. for (int choice : new int[]{2,4}) {
  2. int result = switch (choice) {
  3. case 1, 2, 3 -&gt; 5; // returns 5 for 1,2, or 3
  4. case 4, 5, 6 -&gt; { // similar for 4,5,or 6
  5. System.out.println(&quot;returning 6&quot;);
  6. yield 6;
  7. }
  8. default -&gt; 1;
  9. };
  10. System.out.println(&quot;result = &quot; + result);
  11. }

prints

  1. result = 5
  2. returning 6
  3. result = 6
  4. </details>
  5. # 答案3
  6. **得分**: 0
  7. 你的第一个`switch`在下面的代码执行之前终止。如果你想让`case 2`执行下面的代码,那么代码必须在`case 2``body`内。
  8. `case 1`结束前添加`break`,以确保`case 2`不会执行。
  9. ```java
  10. public static void main(String[] args) throws IOException {
  11. while (true) {
  12. System.out.println("登录到管理员网站(1)或进入商店前台(2)?");
  13. int choice = scnr.nextInt();
  14. switch (choice) {
  15. case 1:
  16. StoreFront server = new StoreFront(0);
  17. server.start(6666);
  18. break; // 在这里停止执行
  19. case 2:
  20. // 不要在这里关闭switch
  21. inventoryManager.initializeInventoryFromFile("inventory.json");
  22. System.out.println("欢迎来到游戏商店\n");
  23. System.out.println("请选择菜单中的一个选项");
  24. System.out.println("***************************************");
  25. System.out.println("************主菜单 ******************\n");
  26. while (true) {
  27. System.out.println("输入以下选项之一:\n\n'1':查看产品\n'2':购买产品\n'3':退货\n'4':退出");
  28. int menuChoice = scnr.nextInt();
  29. switch (menuChoice) {
  30. case 1:
  31. viewProducts();
  32. break;
  33. case 2:
  34. purchaseProducts();
  35. break;
  36. case 3:
  37. returnProducts();
  38. break;
  39. case 4:
  40. System.out.println("谢谢光临。请再次光临。");
  41. System.exit(0);
  42. break;
  43. default:
  44. System.out.println("无效选项。请选择1-4之间的选项");
  45. scnr.close();
  46. }
  47. }
  48. }
  49. }
  50. }
英文:

Your first switch terminates before the execution of code below. If you want case 2 to run below code then the code must be in the body of case 2.
add break before ending of case 1 to make sure case 2 does not run.

  1. public static void main(String[] args) throws IOException {
  2. while (true) {
  3. System.out.println(&quot;Login to Admin site (1) or go to store front (2)?&quot;);
  4. int choice = scnr.nextInt();
  5. switch (choice) {
  6. case 1:
  7. StoreFront server = new StoreFront(0);
  8. server.start(6666);
  9. break; //stops execution here
  10. case 2:
  11. //} //don&#39;t close switch here
  12. inventoryManager.initializeInventoryFromFile(&quot;inventory.json&quot;);
  13. System.out.println(&quot;Welcome to the Game Store \n&quot;);
  14. System.out.println(&quot;Please select an option from the menu&quot;);
  15. System.out.println(&quot;***************************************&quot;);
  16. System.out.println(&quot;************MAIN MENU ******************\n&quot;);
  17. while (true) {
  18. System.out.println(&quot;Enter one of the following:\n\n&quot; + &quot;&#39;1&#39; : View Products\n&quot; + &quot;&#39;2&#39; : Purchase Products\n&quot;
  19. + &quot;&#39;3&#39; : Return Products\n&quot; + &quot;&#39;4&#39; : Exit&quot;);
  20. int menuChoice = scnr.nextInt();
  21. switch (menuChoice) {
  22. case 1:
  23. viewProducts();
  24. break;
  25. case 2:
  26. purchaseProducts();
  27. break;
  28. case 3:
  29. returnProducts();
  30. break;
  31. case 4:
  32. System.out.println(&quot;Thank you for coming by. Please come again.&quot;);
  33. System.exit(0);
  34. break;
  35. default:
  36. System.out.println(&quot;INVALID OPTION. Please select an option 1-4&quot;);
  37. scnr.close();
  38. }
  39. // server.cleanUp();
  40. }//close switch here
  41. }
  42. }
  43. }
  44. }

huangapple
  • 本文由 发表于 2023年6月22日 03:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定