This site requires JavaScript, please enable it in your browser!
Greenfoot back
Mariachi
Mariachi wrote ...

2014/12/13

Change if...else if in switch

Mariachi Mariachi

2014/12/13

#
Hi, I wondered if it was possible to change if else if in switch in this kind of code? I shall like relieving the code.
 if (Level.level <= 0) 
        {
            setBackground(new GreenfootImage("Backgroundtutorial.gif"));
            // Le lvl 0 a l'image de Mountains en background.
            level0.playLoop(); //La musique sympa pour le niveau 0.
        }
        else if (Level.level <= 6) 
        {
            setBackground(new GreenfootImage("Backgroundtuto.gif"));
            // Le lvl 0 a l'image de Mountains en background.
            level0.playLoop(); //La musique sympa pour le niveau 0.
        }
Super_Hippo Super_Hippo

2014/12/13

#
You could, but it wouldn't make much sense.
switch(Level.level)
{
    case 0: ... break;
    case 1: case 2: case 3: case 4: case 5: case 6: ... break;
}
Mariachi Mariachi

2014/12/13

#
But Where do I have to implant setBackground and playLoop?
Super_Hippo Super_Hippo

2014/12/13

#
In the "..." part.
Mariachi Mariachi

2014/12/13

#
Ok Thank you, why did you say that it would'nt make much sense ?
Mariachi Mariachi

2014/12/13

#
And where do I have to add <= *number of the level* ?
danpost danpost

2014/12/13

#
In the switch code Super_Hippo gave, line 3 would be like your 'if' part. All valid 'Level.level' values must be explicitly cased (all possible values less than or equal to zero). Line 4 is like your 'else if' part (all possible value less than or equal to six, but greater than zero). I believe what was meant by it would not make much sense is that you have to basically list all the possible values for each case; and, in your case, it would make more sense to just use an 'if-else if'. Here is another way to write the snippet:
if (Level.level <= 6)
{
    String bg = "Backgroundtuto.gif";
    if (Level.level <= 0) bg = "Backgroundtutorial.gif";
    setBackground(bg);
    level0.playLoop();
}
Mariachi Mariachi

2014/12/13

#
I understand thank you !
You need to login to post a reply.