這是我的代碼片段。我已經修復了這個錯誤,但我現在不明白它爲什麼起作用。我不確定是否正確解釋了這一點,如有必要,請提出任何問題。錯誤在於變量的文字更改爲正確的值測試當語句位於我評論的地方時,語句有效。但是,當聲明位於我評論的地方時,聲明不起作用,聲明不起作用。與此特定程序的變量範圍相混淆
if (endOfSen) {
/////////////////The statement below works when it is here./////////////
/////////////////OUTPUT 1 - occurs when the statement is placed here.
String puncation = null ;
/////////////////////
int orgSize = words.size(); //remember size of stack
//only runs if stack is not empty
if (!words.empty()) {
while (words.size() > 0) { //until last word
String word = words.pop();
///The statement below does not work when it is here///////
//////OUTPUT 2- occurs when the statement is placed here.
//String puncation = null ;
//if last word of sentence
if (orgSize == words.size() + 1) {
word = word.substring(0, 1).toUpperCase() + word.substring(1);
puncation = "test"; // just a test value
word = word.replace(puncation, "");
//////////////////test to see if works
System.out.println("puncation: " + puncation);
}
//if first word of sentence
if (words.size() == 0) {
//////////////////test to see if works
System.out.println("puncation: " + puncation);
word = word.toLowerCase();
word = word + "" + puncation;
}
newSen.push(word);
}
}
endOfSen = false;
}
}
輸出1(第二puncation從原始值的變化)
puncation: test
puncation: test
輸出2(第二puncation不會從原始值改變)
puncation: test
puncation: null
錯誤是什麼?你改變了什麼? – TinyTheBrontosaurus
請指定輸出1何時發生,何時輸出2發生 –
@TinyTheBrontosaurus我做了一個編輯,不知道它是否有幫助。 – name