我正在阅读 Head First Java,一个练习让我有点困惑。练习的原始说明无关紧要,但重点是能够在不编译代码并运行它的情况下解决它,这只会吐出答案。我很困惑,正在尝试播放调试器并逐步执行每一行代码,看看发生了什么。我已将我的评论添加到代码中以确保我理解它。只需要帮助了解例如在特定点的计数是多少等。这是原始代码,我自己添加了一行,我已经注意到了。我会注意一些我不太理解的行。
**更新:所以我对我的代码给出了最好的理解。我对某些行的问题在评论中。如果有人可以逐步了解所发生的事情,那将会更容易理解。提前感谢大家的帮助。我是 StackOverFlow 的新手,所以希望这是提出问题的正确方法。
public class Mix4
{
int counter = 0; //This is setting the variable counter to 0.
public static void main (String[] args)
{
int count = 0; //This is setting the variable count to 0.
Mix4[] m4a = new Mix4[20];//This is initializing an array of 20 m4a objects to null.
int x = 0; //This is setting the variable x to 0;
while ( x < 9 )
{
m4a[x] = new Mix4(); //This actually creates the m4a object at array index 0.
m4a[x].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
count = count + 1; //This increments the variable count. Why do this though?
count = count + m4a[x].maybeNew(x);
//The count variable again is being implemented but this time it calls the
// maybeNew method and it is passing a 0 as as the argument? Why do this?
x = x + 1; // x is being incremented.
System.out.println(count + " " + m4a[1].counter);
//What is this printing and when does this print?
}
public int maybeNew(int index)
{
if (index < 5)
{
Mix4 m4 = new Mix4(); //Creating a new object called m4.
m4.counter = m4.counter + 1;
//Same question about this from the code of line stated above using dot
//operators on variables.
return 1; //Where does 1 be returned to? I thought you can only have one
//return statement per method?
}
return 0; // I thought only 1 return statement? I have no idea what these return
// statements are doing
}
}
}