需要帮助模拟程序,模拟小偷窃取电视

时间:2012-02-19 03:13:39

标签: java arrays class data-structures for-loop

现在拿起一本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 个答案:

答案 0 :(得分:0)

你的问题基本上就在这里

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

第一个问题是代码无法编译,因为array在main中定义,在此范围内不可见。接下来的数组属于House类型,因此无法使用+运算符。

victimNumber始终为零,因此循环永远不会执行。

也许用

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