-2
package javaapplication54;

public class JavaApplication54 {

static int monkey = 8;
static int theArray[] = new int[1];

public static void main(String[] args) {
// i attempted two ways to try to set monkey to = theArray[0];
    monkey = theArray[0];
    theArray[0] = monkey;
//i tried to get the result 8;
    System.out.println(theArray[0]);

}

}

我试图通过打印出 theArray[0] 来获得结果 8,但结果为零。

          run:
   0
 BUILD SUCCESSFUL (total time: 0 seconds)
4

4 回答 4

2

您在第一次在行初始化时分配theArray[0]的行:monkey = theArray[0]theArray[0]0theArray

static int theArray[] = new int[1];
于 2013-07-18T03:53:28.873 回答
2

您正在使用int原语,因此它默认为 0。

让我逐段分解您的代码,以便您理解这一点。

在这里你说monkey是8

static int monkey = 8;

在这里你创建一个新数组

static int theArray[] = new int[1];

此时,数组只包含0,因为它是int变量的默认值。所以,theArray[0]等于0

在这里,您得到了它0并将其分配给猴子,其先前的值为8

monkey = theArray[0];

然后你得到了那个新分配的猴子,它现在等于0,并将它分配给theArray[0]

theArray[0] = monkey;

所以theArray[0]这相当于0现在相当于......是的,0.

最后但并非最不重要的一点是,您0使用System.out.println(theArray[0]);

这就是为什么你得到0而不是8.

于 2013-07-18T04:20:45.513 回答
1

int始终具有0默认值,因此它按预期工作。

如果您希望它指向8,请先将其保存在临时变量中,然后再分配monkey给其他地方。

于 2013-07-18T03:53:42.373 回答
0

main 方法中的第 1 行将 monkey 的值替换为存储在 theArray[0] 中的值,在本例中是默认的 int 值 (0)。第 2 行将 theArray[0] 的值设置为 monkey,因此 monkey(8) 的初始值完全丢失。如果您想将猴子变量存储在 theArray[0] 中,也许这就是您可以尝试的,

public class JavaApplication54 {

static int monkey = 8;
static int theArray[] = new int[1];

public static void main(String args[])
{
theArray[0]=monkey;
System.out.println(theArray[0]);
}

输出:- 8

还要考虑数组和变量都是 static 的事实,这是必需的,因为您在静态方法中使用它们,但是如果您从代码中的任何位置更改其值,它将在任何地方反映更改。

http://www.caveofprogramming.com/java/java-for-beginners-static-variables-what-are-they/

于 2013-07-18T04:27:00.757 回答