这是我程序的最后一个代码部分,我无法使其正常工作:
问题在于,当我打印出来时,程序使用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());
答案 0 :(得分:5)
那是因为你只是在修改构造函数的参数变量而不是你的实例变量。所以,只需像这样修改构造函数:
public Sentence(String[] words){
this.words = words;
}
请注意,声明与实例变量同名的局部变量称为 shadowing ,有关此内容的更多信息可在Wikipedia中找到:
在计算机编程中,变量时会发生变量阴影 在一定范围内宣布(决策块,方法或内部 class)与在外部作用域中声明的变量具有相同的名称。
答案 1 :(得分:3)
在构造函数中,您需要将参数分配给实例变量:
public Sentence(String[] words){
this.words = words;
}