程序的最后一点我无法开始工作。 (构造函数)

Final bit on program I can't get working. (Constructors)

这是我程序的最后一段代码,我无法让它运行:

问题是当我打印出来时,程序使用了words实例变量。

如何更改代码以便在下面的主要方法中使用 wordList?这是我必须在构造函数中更改的内容吗?

import java.util.Arrays;

public class Sentence {
private String[] words = {""}; // My private instance variable. 
//Supposed to hold  the words in wordList below.

public Sentence(String[] words){ // Constructor which I'm pretty sure is not 100% right
//Elements of array will be words of sentence. 
}

public String shortest() {
    String shortest = "";

    for (int i = 0; i < words.length; i++) {
        if(shortest.isEmpty())
            shortest = words[i];
        if (shortest.length() > words[i].length())
            shortest = words[i];
    }
    return shortest;
}


public static void main(String[] args) {

String[] wordList = {"A", "quick", "brown", "fox", "jumped",
             "over", "the", "lazy", "dog"};
Sentence text = new Sentence(wordList);
System.out.println("Shortest word:" + text.shortest());

那是因为你只是修改了构造函数的参数变量,而不是你的实例变量。所以,只需像这样修改构造函数:

public Sentence(String[] words){ 

this.words = words;

}

请注意,声明一个与实例变量同名的局部变量被称为 阴影,有关此的更多信息可在 Wikipedia 中找到:

In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope.

在您的构造函数中,您需要将参数分配给您的实例变量:

public Sentence(String[] words){
    this.words = words;
}