简体   繁体   中英

Why am I getting an error for index 0 out of bounds for length 0 when trying to print separate rows of stars?

I expected it to print the stars. The results were that it printed the stars in the way I wanted, but I got an error when testing saying, "ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0". Code:

public class Printer {

    public static void main(String[] args) {
        // You can test the method here
        int[] array = {5, 1, 3, 4, 2};
        printArrayInStars(array);
   }

    public static void printArrayInStars(int[] array) {
        // Write some code in here
   
         int i = 1;
        while (i<=array[0]) {
            System.out.print("*");
            i++;           
        }
        System.out.println("");
    
        int a = 1;
        while (a<=array[1]) {
            System.out.print("*");
            a++;           
        }
        System.out.println("");
    
        int b = 1;
        while (b<=array[2]) {
            System.out.print("*");
            b++;           
        }
        System.out.println("");
    
        int c = 1;
        while (c<=array[3]) {
            System.out.print("*");
            c++;           
        }
        System.out.println("");

        int d = 1;
        while (d<=array[4]) {
            System.out.print("*");
            d++;           
        }
        System.out.println("");
    }
}

Results:




**

Here's a simple way to loop an array and print array[i] amount of * there are better ways but this is probably the simplest one.

public static void main(String[] args) {
    // You can test the method here
    int[] array = {5, 1, 3, 4, 2};
    for(int i=0;i<array.length;i++)
    {
        printArrayInStars(array[i]);
    }
}

public static void printArrayInStars(int n) {
    // Write some code in here
    for(int i=0;i<n;i++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

Outputs

*****
*
***
****
**

你可以看到这个片段

buddy here is the picture, I posted as you can see no runtime error, you might changing your compiler, or copy and paste to new java file and run it again

class star
{
    public void series()
    {
        String [] a = {"*","*","*","*"};
        for(int i=0; i<4; i++)
        {
            for(int j=0; j<4;j++)
            {   
                System.out.printf(a[j]);
            }System.out.printf("\n");
        }
    }
    public static void main(String [] args)
    {
        star s = new star();
        s.series();
    }
}

output will be 4 line of stars, each line will have 4 stars

if expect something else, please clear your question. n what manner you wanna print stars.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM