user2555471
user2555471

Reputation: 31

Printing an array of a specific size in java

I'm trying to print out an array of 10 objects. For some reason though, when I print out the array, there are anywhere from 15 to 22 elements in the array. I can't figure out why. Can someone please point me in the right direction?

import java.util.Random;

public class Main {
    public static void main( String[] args ) {

        Shape[] myShapes = new Shape[10]; //Array of 10 shapes
        Random rand = new Random(); //Random number generator
        int shape, x1, y1, x2, y2, x3, y3;
        double radius;

        for( int i = 0; i < 10; i++ ) {
            shape = rand.nextInt(3); //randomly select shape
            switch( shape ) {
                case 0: //Triangle
                    x1 = rand.nextInt(101);
                    y1 = rand.nextInt(101);
                    x2 = rand.nextInt(101);
                    y2 = rand.nextInt(101);
                    x3 = rand.nextInt(101);
                    y3 = rand.nextInt(101);
                    myShapes[i] = new Triangle( x1, y1, x2, y2, x3, y3 );
                    System.out.println("Triangle: " + myShapes[i].area());

                case 1: //Rectangle
                    x1 = rand.nextInt(101);
                    y1 = rand.nextInt(101);
                    x2 = rand.nextInt(101);
                    y2 = rand.nextInt(101);
                    myShapes[i] = new Rectangle( x1, y1, x2, y2 );
                    System.out.println("Rectangle: " + myShapes[i].area());

                case 2: //Circle
                    radius = rand.nextDouble()*100.0;
                    x1 = rand.nextInt(101);
                    y1 = rand.nextInt(101);
                    myShapes[i] = new Circle( radius, x1, y1 );
                    System.out.println("Circle: " + myShapes[i].area());
            }
        }
    }

Upvotes: 0

Views: 97

Answers (1)

Kartic
Kartic

Reputation: 2985

Can you please use break; for each case?

Your array actually has 10 elements. But it puts content in each elements up to three times - because control continues from case to case. Thus, if case 0 is right, it will put three shapes and print three prints. If case 1 is right, it will put two shapes and print two prints.

If you put break after each case, then on each iteration it will just put one shape and print just once.

Upvotes: 3

Related Questions