[英]Final bit on program I can't get working. (Constructors)
這是程序的最后一個代碼部分,我無法使其工作:
問題是當我打印出來時,程序使用words
instance variable。
如何更改代碼,以便可以在下面的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());
那是因為您僅修改構造函數的參數變量,而不是實例變量。 因此,只需像這樣修改構造函數:
public Sentence(String[] words){
this.words = words;
}
注意,聲明與實例變量同名的局部變量稱為陰影 ,有關更多信息,請參見Wikipedia :
在計算機編程中,當在某個范圍(決策塊,方法或內部類)中聲明的變量與在外部范圍中聲明的變量具有相同的名稱時,就會發生變量陰影。
在構造函數中,您需要將參數分配給實例變量:
public Sentence(String[] words){
this.words = words;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.