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

2014/5/31

switch statement

davemib123 davemib123

2014/5/31

#
Hi all, just trying out a switch statement, my question relates to the case element. How can the case use an operator like >= or <= ? As I'm trying to add different enemy patterns based on the random number selected. You can see my attempt below which work only with a =
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (selection == 1)
        {
            int enemySelection = Greenfoot.getRandomNumber(10);
            switch (enemySelection )
            {
                case 1:
                enemySelection = 6;
                moveLeft();
                break;
                case 2:
                enemySelection = 5;
                moveLeftDown();
                break;
            }
            enemyBoundary();
        }
    }
davemib123 davemib123

2014/5/31

#
I've tried this way, is there a better method?
1
2
3
4
5
6
7
8
9
10
11
12
13
switch (enemySelection)
            {
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                moveLeftDown();
                break;
                default:
                moveLeft();
                break;
            }
lordhershey lordhershey

2014/5/31

#
This is not a bad solution, I do not think Java has a is in type operator.
davmac davmac

2014/5/31

#
How can the case use an operator like >= or <= ?
It can't; but you can use if ... else if ... etc.
davemib123 davemib123

2014/5/31

#
Thanx for the replies.
You need to login to post a reply.