HISTOGRAM (Array = Stars Output)

左心房为你撑大大i 提交于 2019-12-13 09:47:39

问题


HISTOGRAM:
I have problem in my code..
The Intended Output must be something Like this:

Output:

0 8 ********  
1 6 ******   
2 3 ***  
3 7 *******

But mine shows:

0 8 *******************************    
1 6 *******************************
2 3 *******************************  
3 7 *******************************

I've searched and compare it to my code but nothing really helps me though..

Can you kindly take a look at my code and give some suggestions, and comments on

how could I code the intended output properly..

Any Help is Appreciated ...

    public static void main(String args[]) {
        {

        StringBuilder stringBuilder = new StringBuilder();

             int n = 0;
            n  = Integer.parseInt(JOptionPane.showInputDialog("Enter value"));

            int[] arr = new int[n];
             String stars = "";
             int input = 0;



            for(int c = 0; c<n; c++ ){
            input  = Integer.parseInt(JOptionPane.showInputDialog("Enter number"));
            arr[c]=input;


             for(int i=0; i<input; i++){ 
                        stringBuilder.append("*"); 
                 }


                 }
            for(int i=0; i<input; i++){ 
                stringBuilder.append("*"); 
            }

                for (int o = 0; o<n ; o++){ 
                stars = stringBuilder.toString();
                System.out.println( o +" "+arr[o]+" "+stars);
                }



        }
        }
    }

回答1:


Every time you append the * in the builder object, clear the previous content. You can use stringBuilder.setLength(0);

import javax.swing.*;

public class Prop {
  public static void main(String args[]) {

    StringBuilder stringBuilder = new StringBuilder();

    int n = 0;
    n  = Integer.parseInt(JOptionPane.showInputDialog("Enter value"));

    int[] arr = new int[n];
    String stars = "";
    int input = 0;

    for(int c = 0; c<n; c++ ){
      input  = Integer.parseInt(JOptionPane.showInputDialog("Enter number"));
      arr[c]=input;

      for(int i=0; i<input; i++){
        stringBuilder.append("*");
      }
      stars = stringBuilder.toString();
      System.out.println( c +" "+arr[c]+" "+stars);
      stringBuilder.setLength(0);             // Reset the `stringBuilder` once pattern is written
    }
  }
}

Output:

0 8 ********  
1 6 ******  
2 3 ***  
3 7 *******  


来源:https://stackoverflow.com/questions/33029885/histogram-array-stars-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!