現在拿起了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.");
}
}
替換爲「需要幫助的模擬程序,模擬了一個賊偷電視」 - 在工作哇,社會造型!嗯,我需要一臺新電視機...... – 2012-02-19 03:18:33
我認爲這很聰明。我很驚訝在教科書中看到類似的東西哈哈 – Methos 2012-02-19 03:23:20
它看起來不像你的數組[]變量的範圍是正確的。你可以在你的steal函數中調用array [],而不用將它實例化爲一個類變量。 – Alastair 2012-02-19 03:35:58