英文:
Need help using StdDraw to draw a 2D array
问题
以下是您要求的翻译部分:
public static void drawBoard(String[][] board) {
for (int i = 0; i < board.length; i++) { //line 88
for (int j = 0; j < board[0].length; j++) {
int r = board.length;
int c = board[0].length;
double R = new Double(r);
double C = new Double(c);
StdDraw.setXscale(0, C);
StdDraw.setYscale(0, R);
StdDraw.setCanvasSize(500, 500);
StdDraw.setPenRadius(0.05);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.rectangle((C / 2), (R / 2), (C / 2), (R / 2));
StdDraw.close();
}
}
}
关于如何修复问题以及如何绘制矩形,您在代码中似乎有一些问题。如果您需要更详细的解释和修复建议,请随时询问。另外,您提到了"java.lang.NullPointerException"错误,可能是因为代码中的某个变量为null,需要检查并解决。
英文:
So I already have a method which reads a file which I have converted into a 2d array(therefore the dimensions of the array could be different each time depending on which file I use). Now I am trying to draw a rectangle using this and it wont work. My code is:
public static void drawBoard(String [][] board) {
for (int i = 0; (i < board.length); i++) { //line 88
for (int j = 0; (j < board[0].length); j++) {
int r = board.length;
int c = board[0].length;
double R = new Double(r);
double C = new Double(c);
StdDraw.setXscale(0,C);
StdDraw.setYscale(0,R);
StdDraw.setCanvasSize(500,500);
StdDraw.setPenRadius(0.05);
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.rectangle((C/2), (R/2), (C/2), (R/2));
StdDraw.close();
}
}
}
What can I do to fix this? How can I get it to draw a rectangle?
it says the error is in line 88 and that its a "java.lang.NullPointerException" error.
答案1
得分: 0
StdDraw.rectangle
期望输入参数的类型是 double
。您传递给它的输入参数类型是 int
。这是可以的,但您可能不希望这样做。当计算 C/2
和 R/2
时,您执行了整数除法,因此您可能会意外地向下取整。为了修复这个问题,您可以将 C
和 R
初始化为 double
。
英文:
StdDraw.rectangle
expects input parameters of type double
. You pass it input parameters of type int
. This is ok but you might not want to do this. When calculating C/2
and R/2
you do integer division and thus you might accidentially round down. To fix this, you could initialize C
and R
as double
.
专注分享java语言的经验与见解,让所有开发者获益!
评论