0
package main;

public class Practice {

    public static void main(String[] args) {
        int array[] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1};
        
        int base10=0;
        for (int j=1; j <=100; j+=10) {
            System.out.print(j + " - " + (base10+=10) + "  | " );
            for (int index = j ; index <= base10 ; index ++) {

                while(array[index] > 0) {
                    System.out.print("*");
                    array[index]--;
                }
            }
            System.out.println();
        }
    }
}

I want to display, one asterisk(*) for each value within the range between 1 to 10, 11 to 20, and so on. Here is my code but I am getting error! This is the output:

1 - 10  | *******************************************************************
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
    at main.Practice.main(Practice.java:25)
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Himu21
  • 88
  • 1
  • 8
  • This is the output - 1 - 10 | ********************************************************************************* Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 at main.Practice.main(Practice.java:25) – Himu21 Jul 18 '20 at 05:01
  • Your `index` gets too large. The `array` has only 10 elements so `index` must be between 0 and 9 (inclusive). – Henry Jul 18 '20 at 05:06

1 Answers1

0

It seems like the array[] stores the length of bar. And you want to print result as followed

1 - 10  | *******************
11 - 20  | ***
21 - 30  | ***************
31 - 40  | *******
41 - 50  | ***********
51 - 60  | *********
61 - 70  | *************
71 - 80  | *****
81 - 90  | *****************
91 - 100  | *

This is my solution code:

    public static void main(String[] args) {
        int array[] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1};
        int index = 0;
        int base10=0;
        for (int j=1; j <=100; j+=10) {
            System.out.print(j + " - " + (base10+=10) + "  | " );
            while(array[index] > 0) {
                System.out.print("*");
                array[index]--;
            }
            index++;
            System.out.println();
        }
    }
dyy.alex
  • 514
  • 2
  • 4
  • 16