-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 に答える
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 に答える