我只是想编写一个程序,该程序在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

09-25 17:20