2013-07-18 57 views
-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]); 

} 

}解释该代码(没有得到结果,我需要)

我想要得到的结果8,通过打印出theArray [0],但结果是零。

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

不要尝试两种不同的方式在同一时间! 'theArray [0] =猴子;'是正确的。 –

回答

2

该行你monkey = theArray[0]theArray[0]0当你第一次在行初始化theArray分配theArray[0]

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

+1,就这么简单。 – TheBlastOne

1

int总有0为默认值,所以它的工作如预期。

如果您希望它指向8,请在将monkey分配到其他位置之前先将其保存在临时变量中。

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

最后但并非最不重要的,您打印0System.out.println(theArray[0]);

这就是为什么你要0而不是8

0

main方法中的第1行将猴子的值替换为存储在数组Array[0]中的值,在这种情况下,它是默认的int值(0)。 第2行将数组[0]的值设置为猴子,因此猴子(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

还要考虑一个事实,即这两个阵列和变量是静态的,这是需要的,因为你在静态方法中使用它们,但是如果你从代码中的任何地方改变它的值,它会反映到处都是变化。

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