gpt4 book ai didi

java - 在哪个更好的示例中可以表示 Java 中的 switch 语句?

转载 作者:行者123 更新时间:2023-11-29 06:25:05 24 4
gpt4 key购买 nike

我敢肯定有比我更好的例子:)

假设下雪了,用户可以为每一片雪花赚取积分,但他们必须快速下雪才能不被雪困住,所以这是我的前任:

class apples{
public static void main(String args[]){
int points;
points = 1;

switch (points){
case 1:
System.out.println("32");
break;
case 2:
System.out.println("Almost half");
break;
case 3:
System.out.println("You're near");
break;
case 4:
System.out.println("Congratulations., You got 100 points");
default:
System.out.println("Want to start again?");
break;
}
}
}

最佳答案

switch 语句被误用了很长时间。

最初的想法是有一个入口点系统;类似 goto 的语句,其工作方式如下:

If my value is 1; goto 1;
Else If my value is 2; goto 2;
Else If my value is 3; goto 3;
Else If goto default;
label 1 : ...;
label 2 : ...;
label 3 : ...;
label default : ...;

人们开始喜欢这个系统,并认为它比有很多 if/else 语句要好。所以他们使用了一个小技巧,break; 现在人们真的很喜欢用 switch 作为 if/else 的替代品,打破 switch 的每一个 case。

要获得原始 switch 语句的一个非常好的示例,您应该有这样的东西:

public void printDaysLeftUntilNextMonday(){
switch(dayOfWeek){
case 1 :
System.out.println("Monday");
case 2 :
System.out.println("Tuesday");
case 3 :
System.out.println("Wednesday");
case 4 :
System.out.println("Thursday");
case 5 :
System.out.println("Friday");
case 6 :
System.out.println("Saturday");
case 7 :
System.out.println("Sunday");
}
}

那天我有一个真实的用例(如果你不滥用 break 就很少见;在 switch 中)它在 Hangman 中。

public void printHangman(){
switch(triesLeft){
case 1 :
printLeftLeg();
case 2 :
printRightLeg();
case 3 :
printLeftArm();
case 4 :
printRightArm();
case 5 :
printBody();
case 6 :
printHead();
}
}

关于java - 在哪个更好的示例中可以表示 Java 中的 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3507334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com