【问题标题】:Need help simulating program that simulates a thief stealing televisions需要帮助模拟模拟小偷偷电视的程序
【发布时间】:2012-02-19 03:13:38
【问题描述】:

现在拿起一本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.");

  }
}

【问题讨论】:

  • “需要帮助模拟模拟小偷偷电视的程序” - 哇,工作中的社交建模!嗯,我需要一台新电视....
  • 我自己认为这很聪明。我很惊讶在教科书中看到这样的东西哈哈
  • 看起来你的 array[] 变量的范围不正确。您在窃取函数中调用 array[] 而不将其实例化为类变量。
  • 其次,我的猜测是你想遍历房屋,挨家挨户偷走房子里的电视。我要做的是在静态窃取函数中接受房屋数组作为参数,并遍历该列表,在每个房屋上调用窃取函数。该示例可能试图教的是块操作的抽象。
  • 谢谢,伙计。非常感激。在过去的 3 个小时里,我基本上一直盯着我的屏幕试图弄清楚这一点。我想我会来这里寻求帮助。但是你是说我应该把数组作为类变量然后返回到steal方法中吗?还是在steal方法中制作数组?

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


【解决方案1】:

你的问题根本就在这里

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());
}

【讨论】:

  • 这真的很有帮助。经过几分钟的调整,我的代码可以完美运行。谢谢。
  • 干杯。如果一切正常且正常工作,请记住将问题标记为已回答。
猜你喜欢
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多