2012-02-19 63 views
0

現在拿起了Java教科書。實際上試圖再次學習語言。需要幫助模擬程序,模擬竊賊偷電視

本書中有一段非常有趣的代碼,它包含一個名爲House的類,用於模擬竊取人們房屋(也是類)的電視的小偷。

唯一的問題是我似乎無法弄清楚如何修改我的數組來更改小偷收集的房屋數量。這很難解釋,但現在是我的代碼。我現在完全迷失了。我真的無法理解陣列是如何工作的,這正在擾亂我的地獄。任何幫助,將不勝感激。

import java.util.Scanner; 
class House { 
    public int nHDTVs; 
    public House pFriend; 
    public House(int nParameter, House friendParameter) 
    { 
    nHDTVs = nParameter; 
    pFriend = friendParameter; 
    } 
    public void steal(House thiefsHouse, House firstVictim) 
    { 
    int nTVsStolen = 0; 
    int victimNumber = 0; 
    for(int i =0; i<victimNumber; i++) 
    { 
    nTVsStolen = nTVsStolen + array[i]; 
    } 
    //nTVsStolen = nTVsStolen + 
    /*for(i=1;i>10;i++) 
    { 
     //stuff 
    }*/ 
    //thiefsHouse nHDTVs = n 


    System.out.println("Victim " + (victimNumber+1) + " " + "lives at " + firstVictim); 
    System.out.println("Victim " + (victimNumber+2) + " " + "lives at " + firstVictim.pFriend); 
System.out.println("I've just stolen " + 0 + " TVs from the House at " + null); 

    thiefsHouse.nHDTVs = thiefsHouse.nHDTVs + nTVsStolen; 
    } 
    public static void main(String dfgasdfwe[]) { 
    int nHouses; 
    Scanner keyboard = new Scanner(System.in); 
    System.out.println("How many houses should the thief steal from?"); 
    nHouses = keyboard.nextInt(); 
    House array[] = new House[nHouses]; 
    array[nHouses - 1] = new House(3, null); 
    for(int i = nHouses - 2; i>=0; i--) 
    { 
     array[i] = new House(i , array[i+1]); 
    } 
    House thiefsHouse = array[0]; 
    //pFriend nHDTVs[victimNumber] = 0; 
    thiefsHouse.steal(thiefsHouse, thiefsHouse.pFriend); 
    System.out.println("I now have " + thiefsHouse.nHDTVs + " TV sets. HA HA."); 

    } 
} 
+1

替換爲「需要幫助的模擬程序,模擬了一個賊偷電視」 - 在工作哇,社會造型!嗯,我需要一臺新電視機...... – 2012-02-19 03:18:33

+0

我認爲這很聰明。我很驚訝在教科書中看到類似的東西哈哈 – Methos 2012-02-19 03:23:20

+0

它看起來不像你的數組[]變量的範圍是正確的。你可以在你的steal函數中調用array [],而不用將它實例化爲一個類變量。 – Alastair 2012-02-19 03:35:58

回答

0

你的問題是從根本上這裏

int nTVsStolen = 0; 
int victimNumber = 0; 
for(int i =0; i<victimNumber; i++) 
{ 
nTVsStolen = nTVsStolen + array[i]; 
} 

的第一個問題是,代碼將無法編譯,因爲array在主定義,在此範圍內不可見。接下來,數組是House類型,因此不能與+運算符一起使用。

victimNumber始終爲零,因此循環從不執行。

也許與

while(nHDTVs > 0) 
{ 
nHDTVs--; 
nTVsStolen++; 
System.out.println("I stole a TV from this Victim: " + toString()); 
} 
+0

這確實幫助了很多。經過幾分鐘的調整,我的代碼才能完美運行。謝謝。 – Methos 2012-02-19 04:38:10

+0

乾杯。請記住,如果所有事情都已平息並正常工作,請將問題標記爲已回答。 – 2012-02-20 00:19:42