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