簡體   English   中英

在Java中打印特定大小的數組

[英]Printing an array of a specific size in java

我正在嘗試打印出10個對象的數組。 但是由於某種原因,當我打印出數組時,數組中有15到22個元素。 我不知道為什么。 有人可以指出正確的方向嗎?

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());
            }
        }
    }

可以請您休息一下 對於每種情況?

您的數組實際上有10個元素。 但這會使每個元素中的內容最多重復三遍-因為控制會根據情況繼續進行。 因此,如果案例0是正確的,它將放置三個形狀並打印三個打印件。 如果情況1是正確的,它將放置兩個形狀並打印兩個打印件。

如果在每種情況之后都放置break ,則在每次迭代中,它將僅放置一個形狀並僅打印一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM