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

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

Using switch in Java but not sure why it works

问题

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

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

public static void main(String[] args) throws IOException {
    
    while (true) {
        System.out.println("登录到管理员站点(1)或进入商店前台(2)?");
        
        int choice = scnr.nextInt();
        
        switch (choice) {
            case 1:
                StoreFront server = new StoreFront(0);
                server.start(6666);
                break; // 添加这行以确保仅在选择1时执行
            case 2:
                // 这里可以添加进入商店前台的代码
                break;
        }
        
        inventoryManager.initializeInventoryFromFile("inventory.json");
        System.out.println("欢迎来到游戏商店\n");
        System.out.println("请从菜单中选择一个选项");
        System.out.println("***************************************");
        System.out.println("************主菜单 ******************\n");
        while (true) {
            System.out.println("输入以下选项之一:\n\n" + "'1' : 查看产品\n" + "'2' : 购买产品\n"
                + "'3' : 退还产品\n" + "'4' : 退出");
            
            int menuChoice = scnr.nextInt();
            
            switch (menuChoice) {
                case 1:
                    viewProducts();
                    break;
                case 2:
                    purchaseProducts();
                    break;
                case 3:
                    returnProducts();
                    break;
                case 4:
                    System.out.println("感谢光临。请再次光临。");
                    System.exit(0);
                    break;
                default:
                    System.out.println("无效选项。请选择选项1-4");
                    scnr.close();
            } 
        // server.cleanUp();
        }
    }
}

请注意,我在选择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.

	public static void main(String[] args) throws IOException {
while (true) {
System.out.println("Login to Admin site (1) or go to store front (2)?");
int choice = scnr.nextInt();
switch (choice) {
case 1:
StoreFront server = new StoreFront(0);
server.start(6666);
case 2:
}
inventoryManager.initializeInventoryFromFile("inventory.json");
System.out.println("Welcome to the Game Store \n");
System.out.println("Please select an option from the menu");
System.out.println("***************************************");
System.out.println("************MAIN MENU ******************\n");
while (true) {
System.out.println("Enter one of the following:\n\n" + "'1' : View Products\n" + "'2' : Purchase Products\n"
+ "'3' : Return Products\n" + "'4' : Exit");
int menuChoice = scnr.nextInt();
switch (menuChoice) {
case 1:
viewProducts();
break;
case 2:
purchaseProducts();
break;
case 3:
returnProducts();
break;
case 4:
System.out.println("Thank you for coming by. Please come again.");
System.exit(0);
break;
default:
System.out.println("INVALID OPTION. Please select an option 1-4");
scnr.close();
} 
//		server.cleanUp();
}
}
}	
}

答案1

得分: 0

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

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

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

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

switch (choice) {
    case 1:
        StoreFront server = new StoreFront(0);
        server.start(6666);
        break;
    case 2:
        break;
}

if (choice == 1) {
    StoreFront server = new StoreFront(0);
    server.start(6666);
} else if (choice == 2) {

}

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

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

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

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

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

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

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

> "... 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.

switch (choice) {
    case 1:
        StoreFront server = new StoreFront(0);
        server.start(6666);
        break;
    case 2:
        break;
}

if (choice == 1) {
    StoreFront server = new StoreFront(0);
    server.start(6666);
} else if (choice == 2) {

}

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.

switch (choice) {
    case 1 -> {
        StoreFront server = new StoreFront(0);
        server.start(6666);
    }
    case 2 -> { }
}

</details>



# 答案2
**得分**: 0

你的示例中唯一的问题是这一部分
```java
switch (choice) {
       case 1:
            StoreFront server = new StoreFront(0);
            server.start(6666);
                
       case 2:
}

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

上述代码等同于:

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

不要忘记 switch 表达式

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

打印结果为:

result = 5
返回 6
result = 6
英文:

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

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

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

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

And don't forget the switch expression

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

prints

result = 5
returning 6
result = 6
</details>
# 答案3
**得分**: 0
你的第一个`switch`在下面的代码执行之前终止。如果你想让`case 2`执行下面的代码,那么代码必须在`case 2`的`body`内。
在`case 1`结束前添加`break`,以确保`case 2`不会执行。
```java
public static void main(String[] args) throws IOException {
while (true) {
System.out.println("登录到管理员网站(1)或进入商店前台(2)?");
int choice = scnr.nextInt();
switch (choice) {
case 1:
StoreFront server = new StoreFront(0);
server.start(6666);
break; // 在这里停止执行
case 2:
// 不要在这里关闭switch
inventoryManager.initializeInventoryFromFile("inventory.json");
System.out.println("欢迎来到游戏商店\n");
System.out.println("请选择菜单中的一个选项");
System.out.println("***************************************");
System.out.println("************主菜单 ******************\n");
while (true) {
System.out.println("输入以下选项之一:\n\n'1':查看产品\n'2':购买产品\n'3':退货\n'4':退出");
int menuChoice = scnr.nextInt();
switch (menuChoice) {
case 1:
viewProducts();
break;
case 2:
purchaseProducts();
break;
case 3:
returnProducts();
break;
case 4:
System.out.println("谢谢光临。请再次光临。");
System.exit(0);
break;
default:
System.out.println("无效选项。请选择1-4之间的选项");
scnr.close();
}
}
}
}
}
英文:

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.

    public static void main(String[] args) throws IOException {
while (true) {
System.out.println(&quot;Login to Admin site (1) or go to store front (2)?&quot;);
int choice = scnr.nextInt();
switch (choice) {
case 1:
StoreFront server = new StoreFront(0);
server.start(6666);
break; //stops execution here
case 2:
//} //don&#39;t close switch here
inventoryManager.initializeInventoryFromFile(&quot;inventory.json&quot;);
System.out.println(&quot;Welcome to the Game Store \n&quot;);
System.out.println(&quot;Please select an option from the menu&quot;);
System.out.println(&quot;***************************************&quot;);
System.out.println(&quot;************MAIN MENU ******************\n&quot;);
while (true) {
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;
+ &quot;&#39;3&#39; : Return Products\n&quot; + &quot;&#39;4&#39; : Exit&quot;);
int menuChoice = scnr.nextInt();
switch (menuChoice) {
case 1:
viewProducts();
break;
case 2:
purchaseProducts();
break;
case 3:
returnProducts();
break;
case 4:
System.out.println(&quot;Thank you for coming by. Please come again.&quot;);
System.exit(0);
break;
default:
System.out.println(&quot;INVALID OPTION. Please select an option 1-4&quot;);
scnr.close();
} 
//      server.cleanUp();
}//close switch here
}
}
}   
}

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:

确定