Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将数组长度设置为传递给构造函数的值_Java_Arrays_Variables_Constructor - Fatal编程技术网

Java 将数组长度设置为传递给构造函数的值

Java 将数组长度设置为传递给构造函数的值,java,arrays,variables,constructor,Java,Arrays,Variables,Constructor,我正试图创造这样的东西 Class WordStore { private int size; private String words[]; public WordStore(int n) { size=n; words[]=new String[size]; } ... } 因此,我可以将单词作为全局变量,可以从类中的任何方法访问它,而不必将其作为参数传递。数组字的长度必须是传递给构造函数的int值,该值是从另一

我正试图创造这样的东西

Class WordStore {

    private int size;
    private String words[];

    public WordStore(int n) {
        size=n;
        words[]=new String[size];
    }

    ...
}
因此,我可以将单词作为全局变量,可以从类中的任何方法访问它,而不必将其作为参数传递。数组字的长度必须是传递给构造函数的int值,该值是从另一个类传递的。 它必须是数组,而不是ArrayList或任何其他列表


但是目前它还没有编译,我需要做什么更正才能编译它。

words[]=newstring[size];应该是这样的单词=新字符串[n]

这应该足够了

private int size;

private String words[];

public WordStore(int n){
     words =new String[n];
}

如果您不需要像其他回答者所说的那样将尺寸设置为全局尺寸,那么您应该替换

单词[]=新字符串[大小];with words=新字符串[n]

这是因为[]是变量类型的一部分,而不是它的名称。这种混淆是可以理解的,因为在声明变量时,是否将[]与类型的其余部分或名称放在一起是可选的。因此,通常将数组类型的变量声明为

private String[] words; //type: String[] name: words
而不是非标准

private String words[]; //still type: String[] name: words, but less clear
一旦这样做,所有内容都变得更加一致,在使用变量时就不会重复字符串类型,因此也不会重复[]


另外,Class应该是Class,因为在java中关键字是小写的

那么你的问题是什么?你有什么问题吗?你试过你发布的代码了吗?如果是,它是否抛出任何错误?如果是哪一个?去掉作业中的[],但它应该没问题。尽管不需要单独存储大小,但它始终可以作为单词使用。length@Prabhakaran很可能,否决票不是我投的,他们想解释一下为什么这条线可以改变。尽管我想不出任何解释,除了因为java就是这样写的。@user3074612这种混淆可能在很大程度上是由于您如何声明私有字符串[];,[]是类型的一部分,因此更常见的做法是编写私有字符串[]字;,一旦你这样做,很明显,[]不是名字的一部分