java - Trouble with switch statements? -
i trying write program generates random year between 2000 , 2010, reads off space exploration fact occurred in year. code have written, when run it, no matter year generated, prints last case (2010). how fix this?
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 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 comet"; case 2006: eventstring = "2006: spacecraft returns collections comet"; case 2007: eventstring = "2007: n/a"; case 2008: eventstring = "2008: kepler launched study deep space"; case 2009: eventstring = "2009: n/a"; case 2010: eventstring = "2010: spacex sucessfully sends spacecraft orbit , back"; } system.out.println(eventstring); } }
you need add break
statement after each case else after finding matching case execute cases until finds break or end in case 2010
.