Java switch statement ?

Im racking my brain about this. So my teacher gave us challenge to make a random number generator that displays a winning prize if it lands on particular number. I get how to make the random number part but im lost on how to make it true for each case. 

0-9 free drink

10-19  fries

20-39 sub

40 -59 coffee 

>59 nothing 

He told us that the mod would help but i cant seem to make it work any help would be appreciated 


And it was manditory to use a switch statement

2 Answers

  • 4 weeks ago

    Never mind figured it out. And I agree with you integer would have been much easier guess he was just trying to get us to think differently. Thank you for your answe

  • 4 weeks ago

    "mandatory" ... it's derived from the root word "mandate"

    Actually, it's easier with division (assuming that I understand the problem statement).  Here's how I see it.

    Let n be an int variable that holds your random number.  I assume it's not negative, but you haven't specified what the maximum value is.  Then  the expression (n/10) is integer division of n by 10, discarding any remainder.  If n is in 0..9 then n/10 == 0.  If n is in 10..19 then n/10 = 1, etc. That makes a switch statement easy:

    switch (n / 10):

        case 0: { // 0..9

            award free drink;



        case 1: { // 10..19

            award free fries;



        case 2: // 20-29

        case 3: { // and 30-32

            award free sub;



        case 4: // 40-49

        case 5: { // and 50-59

            award free coffee;


        default: { // anything else gets no prize

            [do something, if needed]




    Now, you could use n - n%10 instead.  That will give you numbers 0, 10, 20, 30, ... for your case labels instead of 0, 1, 2, 3, ...; but it's easier to type n/10 and the single-digit case numbers.

    Notice how two or more consecutive case labels can be used to run the same block for any of two or more switch values.  Above, case 2 and case 3 were combined to execute a single block (free sub) if n/10 is either 2 or 3 ... meaning that n was in 20..39.

Still have questions? Get answers by asking now.