【问题标题】:How to print a histogram? [duplicate]如何打印直方图? [复制]
【发布时间】:2013-12-09 06:48:08
【问题描述】:

我正在尝试打印直方图,但在将它们拼凑在一起时遇到了麻烦。我是数组的新手,所以如果有人可以提供帮助,将不胜感激。这是我的方法:

public static void main(String[] args) {
  randomIntArray(5);
}

public static int randomInt(int low, int high){
  int x= (int)(Math.random ()*high)+low;
  return x;       
}

public static int[] randomIntArray(int n){
  int[] a = new int [n];
  for (int i = 0;i<a.length;i++){
    a[i]=randomInt (0,100);
  }

  System.out.println(printHist(a));
  return a;
}

public static int[] printHist(int[]a){
  int[] k = new int[11];
  int i=0;
  while (i<=10) { 
    int counter = 0;
    int h=0;
    while(h<a.length) {
      if (a[h] == i) {
        counter++;
        h++;
      }
      h++;
    }

    k[i] = counter;
    i++;
  }

  return k;
}

这是我得到的输出。

[I@fb53f6

我需要重新考虑我这样做的方式,还是有一个简单的解决方法?

【问题讨论】:

  • 查看Object#toString() 方法及其作用。
  • 试试System.out.println(Arrays.toString(printHist(a)));
  • @ZouZou: 好吧,这有点好,但现在我得到'[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]'。
  • @NickGatti 现在这是另一个问题。你必须调查原因。

标签: java arrays histogram


【解决方案1】:

System.out.println(arrayObject) 并没有按照你的想法去做。

尝试以下相关问题的解决方案之一:What's the simplest way to print a Java array? - 例如Arrays.toString(arrayObject)

【讨论】:

  • 好吧,这有点好,但现在我得到 '[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]'
  • 基于阅读您上面的代码,这听起来像 k[i] = counter 总是分配一个 0 值 - 可能是因为您的内部 while 条件 h&lt;a.length 或 if 条件 a[h] == i 不是遇见了。最好的选择是使用您的调试器并逐步执行代码。
猜你喜欢
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多