使用2D阵列绘图

时间:2016-11-03 19:00:32

标签: java debugging multidimensional-array formatting char

我已经解决了这个问题一段时间了,我似乎无法调试我的程序。 我使用2d数组创建了一个图表,我正在尝试使用' X'在x和y坐标点上。然后我试图在点上绘制最小二乘回归线。 这是我的代码片段:

char[][] graph = new char[21][42];

for (int i = 0; i < count; ++i) {
 graph[21 - 1 - yCoords[i]][xCoords[i] + 1] = 'X';
}

// plot the regression line
for (int i = 0; i < graph.length; i++) {
 int yPred = Math.round(yMean + slope * (i - xMean)); // calculate regression value
 graph[21-1-yPred][i + 1] = graph[21-1-yPred][i + 1 ] == 'X' ? '*' : '-'; //problem somewhere here
}

//This is how i initialized my array
 public static void initializeArray(char[][] charArray) {
  for(int k =0; k< charArray.length; k++) {
      for(int d = 0; d < charArray[0].length;d++) {
        charArray[k][d] = ' ';
      }
    }
  for (int i = 0; i < charArray.length; ++i) {
    charArray[i][0] = '/';
  }
  charArray[20][0] = '+';

  for (int i = 1; i < charArray[0].length; ++i) {
    charArray[20][i] = '-';
  }
}
  

请记住,这不是完整的代码。如果有人很难搞清楚问题,请在下面发表评论,我会解释或提供更多代码来解决我的问题。

现在我收到了这个输出。

enter image description here

我的预期输出为:

enter image description here

问题似乎在于绘制回归线。所以我使用&#34; X&#34;来表示点,&#34; - &#34;是回归线段,&#34; *&#34; s其中一个线段和一个点位于同一地点。 我愿意提供更多细节。任何人都可以帮我解决bug。

1 个答案:

答案 0 :(得分:0)

对于任何面临同样问题的人来说,这就是我所做的以获得正确的输出。 我所要做的就是在循环时输入-1以避免索引越界异常。 ere是代码:

for (int i = 0; i < graph[0].length - 1; i++) {
 int yPred = (int) (yMean + (slope * (i - xMean)));
 if(yPred > 0 && yPred < 21) {
   graph[21 - 1- yPred][i+1] = graph[21 - 1- yPred][i+1] == 'X' ? '*' : '-';
  }