我正在创建一种能够“打印直方图”的方法,并且我试图让它引用histogramData.length,以便能够循环和构建每一行,但它不能识别histogramData。方法中的长度。
我将代码放在2个单独的文件中,一个用于main,另一个用于构建方法。
主要看起来像:
import becker.robots.*;
public class DrawHistogram extends Object
{ public static void main(String[] args)
{ City Edmonds = new City(12, 12);
HistogramRobot drawingBot = new HistogramRobot(Edmonds, 1, 1, Direction.EAST, 1000);
HistogramPrinter histPrinter = new HistogramPrinter();
int [] histogramData = new int[7];
histogramData[0] = 3; // The first element holds 3
histogramData[1] = 5; // The second element holds 5
histogramData[2] = 1; // The third element holds 1
histogramData[3] = 0; // The fourth element holds 0
histogramData[4] = 4; // The fifth element holds 4
histogramData[5] = 2; // The sixth element holds 2
histogramData[6] = 1; // The seventh element holds 1
drawingBot.drawRow();
}
}
我的方法文件看起来像
import becker.robots.*;
class HistogramRobot extends Robot
{
HistogramRobot(City c, int st, int ave, Direction dir, int num)
{
super(c, st, ave, dir, num);
}
public void drawRow()
{
for(int counter = 0; counter < histogramData.length; counter++)
{
if( histogramData[counter] == 0)
{
this.turnRight();
this.move();
this.turnLeft();
}
for( int histoDrop = 0; histoDrop < histogramData[counter]; histoDrop++)
{
this.putThing();
this.move();
}
this.turnAround();
for (int moves = 0; moves < histogramData[counter]; moves++)
{
this.move();
}
this.turnLeft();
this.move();
this.turnLeft();
}
}
public void turnRight()
{
this.turnLeft();
this.turnLeft();
this.turnLeft();
}
public void turnAround()
{
this.turnLeft();
this.turnLeft();
}
}
我每次提到“histogramData”时都会遇到错误,包括“histogramData.length”
HistogramRobot.java:24: error: cannot find symbol
for( int histoDrop = 0; histoDrop < histogramData[counter]; histoDrop++)
^
symbol: variable histogramData
location: class HistogramRobot
导致错误的原因是什么?如何解决?
//对不起!我无法让第二部分的间距对我有利,如果你需要澄清答案,请告诉我。
答案 0 :(得分:1)
你宣布了
int [] histogramData = new int[7];
在您的main
方法中,因此其范围仅限于此方法。
将其作为参数传递给需要的地方
如
drawingBot.drawRow(histogramData);
您的方法声明将是
public void drawRow(int [] histogramData)