2014-06-05 63 views
1

我創建了一個能夠「打印直方圖」的方法,並且我試圖讓它引用histogramData.length,以便能夠循環和構建每一行,但它不能識別方法中的histogramData.length。編譯錯誤:無法找到array.length的符號

我有兩個單獨的文件中的代碼,一個用於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

你的問題是你沒有定義稱爲陣列histogramRobot類中任何位置的histogramData。嘗試將它傳遞給drawRow方法 – JamesENL

回答

1

你已經宣佈你

int [] histogramData = new int[7]; 

main法等其範圍僅限於該方法。

把它作爲參數傳遞給需要它的地方

drawingBot.drawRow(histogramData); 

你方法聲明會

public void drawRow(int [] histogramData) 
+2

histogramData甚至不在您嘗試使用它的同一類中。只是要添加一點:) – Stultuske

+0

@Stultuske謝謝,我已經更新。 –

+0

原諒我,如果我看起來像我知道我在說什麼......但我不知道我會把它放在哪裏呢?我應該把它與創建drawRow方法,還是完全放在一個新文件中? – TaylerMaybe

相關問題