Java 解释此代码(没有得到我需要的结果)

Java 解释此代码(没有得到我需要的结果),java,arrays,Java,Arrays,} 我试图通过打印数组[0]得到结果8,但结果为零 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]

}

我试图通过打印数组[0]得到结果8,但结果为零

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]);

}

当您第一次在第行初始化数组时,您在行
monkey=theArray[0]
中分配了
theArray[0]
哪个
theArray[0]
0

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

int
的默认值始终为
0
,因此它可以按预期工作


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

您使用的是
int
原语,因此它默认为0

让我把你的代码一块一块地分解,这样你就可以理解了

这里您声明
monkey
是8

static int theArray[] = new int[1];
在这里创建一个新数组

static int monkey = 8;
此时,数组只包含
0
,因为它是
int
变量的默认值。因此,
数组[0]
等于
0

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

static int theArray[] = new int[1];
然后你得到了新分配的猴子,它现在等于
0
,并分配给
数组[0]

monkey = theArray[0];
因此,原来与
0
等价的数组[0]现在与。。。是的,
0

最后但并非最不重要的一点是,使用
System.out.println(数组[0])打印
0


这就是为什么在main方法中得到
0
而不是
8

行1将monkey的值替换为数组[0]中存储的值,在这种情况下,该值是默认的int值(0)。 第2行将数组[0]的值设置为monkey,因此monkey(8)的初始值完全丢失。 如果您想在数组[0]中存储monkey变量,也许您可以尝试这样做

theArray[0] = monkey;
产出:-8

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


不要同时尝试两种不同的方法<代码>数组[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]);
}