-1

I'm trying to create a program that prints a number of * equal to each value in an array. I'm doing this by using a method. The first iteration works and prints the number of *. But then my for loop ends and I don't know why.

package problem99_printarrayas_stars;

public class Problem99_PrintArrayAs_Stars {

public static void main(String[] args) {
           int[] array = {5, 1, 3, 4, 2};
           printArrayAsStars(array);

}

public static void printArrayAsStars(int[] array) {
    int a =0;
    for(int i = 0; i<5; i++){
        while(a<array[i]){

        System.out.print("*");
        a++;
        }
  }       
}

}

john
  • 37
  • 5
  • 1
    "*My for loop is breaking after my while loop is finished...*" - No it does not. Please read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Turing85 Jul 27 '19 at 14:50

1 Answers1

0

just put your "a" into your for scope

public static void main(String[] args) {
    int[] array = { 5, 1, 3, 4, 2 };
    printArrayAsStars(array);
}

public static void printArrayAsStars(int[] array) {
    for (int i = 0; i < 5; i++) {
        int a = 0;
        while (a < array[i]) {
            System.out.print("*");
            a++;
        }
        System.out.println();
    }
}
Super Shark
  • 376
  • 3
  • 12
  • 1
    or just move the whole declaration and initialization of `a` inside the loop (one line down ) or, even better IMO, use a second `loop` instead of `while` – user85421 Jul 27 '19 at 14:59