我只是想编写一个程序,生成 2000 年到 2010 年之间的随机年份,然后读出该年发生的太空探索事实。 这是我编写的代码,但是当我运行它时,无论生成哪一年,它都只打印最后一个案例(2010)。我该如何解决这个问题?
import java.util.Random;
public class SpaceExploration {
public static void main(String[] args) {
int year =(int)(Math.random()*11) + 2000;
String eventString = "";
switch (year) {
case 2000: eventString = "2000: First spacecraft orbits an asteroid";
case 2001: eventString = "2001: First spacecraft lands on asteroid";
case 2002: eventString = "2002: N/A";
case 2003: eventString = "2003: Largest infrared telescope released";
case 2004: eventString = "2004: N/A";
case 2005: eventString = "2005: Spacecraft collies with comet";
case 2006: eventString = "2006: Spacecraft returns with collections from a comet";
case 2007: eventString = "2007: N/A";
case 2008: eventString = "2008: Kepler launched to study deep space";
case 2009: eventString = "2009: N/A";
case 2010: eventString = "2010: SpaceX sucessfully sends spacecraft to orbit and back";
}
System.out.println(eventString);
}
}
最佳答案
您需要在每个案例之后添加 break
语句,否则在找到匹配的案例后,它将只执行所有案例,直到找到中断或您的案例中的结尾为 2010
.
关于java - switch 语句有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29814746/