0

I write my code in eclipse, I have a class called platform and subclasses like redplatform, blueplatform.I want to create an arraylist which can store both blueplatform and redplatform,I have done this so far.

ArrayList<Platform> p = new ArrayList<Platform>();
private void createPlatform() {
    switch (platform) {
    case 0:
        p.add(new GreenPlatform(x, y));
    case 1:
        p.add(new RedPlatform(x, y));
    case 2:
        p.add(new BluePlatform(x, y));
    case 3:
        p.add(new MagentaPlatform(x, y));
    case 4:
        p.add(new GrayPlatform(x, y));
    }
repaint();
@Override
public void paintComponent(Graphics g) {
    // TODO Auto-generated method stub
    super.paintComponent(g);
    for (int i = 0; i < p.size(); i++) {
        p.get(i).paint(g);
    }
}

In each class, it has a paint method that sets color to something different and paints it but right now all of them are gray. This is frustrating.

1 Answer 1

3
switch (platform) {
case 0:
    p.add(new GreenPlatform(x, y));
    break;
case 1:
    p.add(new RedPlatform(x, y));
    break;
case 2:
    p.add(new BluePlatform(x, y));
    break;
case 3:
    p.add(new MagentaPlatform(x, y));
    break;
case 4:
    p.add(new GrayPlatform(x, y));
}
Sign up to request clarification or add additional context in comments.

2 Comments

I see, I've been making that mistake! But how does this affect the program? Isn't break just breaking out of the for loop? Since int platform is only one int, one of the cases will execute and the others won't, right?
@yuzhengwen switch works like this: once a case is matched and you don't break it, every statement after that matched case will be executed, even though they are under different cases. For example, if case 2 is matched and you don't use break, everything under case 2, case 3, case 4 will be executed. Read more here: docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.