HISTOGRAM(数组=星形输出)

时间:2015-10-09 04:23:17

标签: java arrays histogram

直方图:
我的代码有问题。
预期输出必须是这样的:

输出:

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

但我的节目显示:

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

我已经搜索并将其与我的代码进行比较但是没有什么能真正帮助我...

请您仔细查看我的代码,并提供一些建议和意见

我怎样才能正确编码预期的输出..

赞赏任何帮助......

    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 个答案:

答案 0 :(得分:1)

每次在构建器对象中追加NSTextTab时,请清除以前的内容。您可以使用*;

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
    }
  }
}