gpt4 book ai didi

java - 简单的Java数组问题

转载 作者:行者123 更新时间:2023-11-30 05:57:27 24 4
gpt4 key购买 nike

为什么这个可以工作,而另一个会抛出错误:

import java.util.*;

//This works fine
public class ArrayTest {
public static String[] names = {"James", "John", "Mark"};
public static void main( String args[] ){
System.out.print("Names: " + Arrays.toString(names));
}
}

//But why does this not?
public class ArrayTest {
public static String[] names = new String[3];
names[0] = "James";
names[1] = "John";
names[2] = "Mark";
public static void main( String args[] ){
System.out.print("Names: " + Arrays.toString(names));
}
}

最佳答案

尝试这样:

public class ArrayTest {
public static String[] names;

static
{
names = new String[3];
names[0] = "James";
names[1] = "John";
names[2] = "Mark";
}

public static void main( String args[] ){
System.out.print("Names: " + Arrays.toString(names));
}
}

关于java - 简单的Java数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5716454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com