程序的最后一点我无法工作.(构造)

Edo*_*dot 1 java constructor instance-variables

这是我的程序的最后一个代码部分,我不能使它工作:

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

如何更改代码,以便我可以在下面的main方法中使用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());
Run Code Online (Sandbox Code Playgroud)

Tar*_*rik 5

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

public Sentence(String[] words){ 

this.words = words;

}
Run Code Online (Sandbox Code Playgroud)

请注意,声明与实例变量同名的局部变量称为阴影,有关它的更多信息可以在维基百科中找到:

在计算机编程中,当在特定范围内声明的变量(决策块,方法或内部类)与在外部范围中声明的变量具有相同的名称时,会发生变量阴影.