dimanche 22 mai 2016

switch statement in generating random numbers in java : not working

I've used a switch statement in my code that tosses a coin and generates a random result. If the coin falls on 0, it shows tails and if it falls on 1, it shows heads. But when I'm using switch statements, the outputs are always either only "heads" or both of "tails' and "heads".

My code:

import static java.lang.System.*;
import java.util.*;

class generateRandomNumbers{
    public static void main(String[] args){
        Random coin = new Random();
        int toss;
        toss = coin.nextInt(2);
        switch(toss){
            case 0 : out.println("tails");
            case 1 ; out.println("heads");
        }
    }
}

But when I used if-else statements it worked as planned:

import static java.lang.System.*;
import java.util.*;

class generateRandomNumbers{
    public static void main(String[] args){
        Random coin = new Random();
        int toss;
        toss = coin.nextInt(2);
        if(toss == 0){
            out.println("tails");
        }
        else{
            out.println("heads");
        }
    }
}

Please point out what my mistake is when I used switch statement in my code




Aucun commentaire:

Enregistrer un commentaire