2012-02-19 61 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