Skip to content
Advertisement

Im trying to make a “graphic” printing a certain amount of characters based on array values java

I have to make a code thats contain a method that takes a vector of integers as a parameter and, from their values, prints a horizontal bar graph on the screen. I Just cant print the amount of characters with the value of the string. Rigth now i have a list in a method:

class Main {  
  public static void main(String args[]) { 
      exibeGraficoDeBarras();
  }
  static void exibeGraficoDeBarras(){
    int lista[]={4,12,10,14,17,9};
    for (int i = 0; i<lista.length; i++ ){
      for (int j = 0; j<lista[i]; j++){
        System.out.print("#");
      }
      System.out.println();
    }
  }
}

And the output should be like this:

“########## 10”

“##### 5”

“####### 7”

Just add the “” cause the formatting

Advertisement

Answer

You need 3 things:

  • for (int i = 0; i < 10; i++) { code goes here } runs the part in ‘code goes here’ 10 times. You can put for loops in the code goes here section too.
  • list[0] accesses the first item in your list (10, in your case). 0 can be i too, of course.
  • System.out.print(thingie) prints things. thingie can be "#" to print a hash, for example, or i, of course, that works too. System.out.println() then finishes the line.
Advertisement