0
我做了一些java家庭工作,我似乎有一個小問題。我的問題是Im試圖引用的變量顯示它沒有被初始化。不過,我在方法的前面聲明瞭變量,然後在循環中初始化了它。當我嘗試訪問變量時,我使用相同的方法在後面幾行調用charCount時,編譯器會抱怨變量仍需要初始化。有人可以解釋爲什麼這是不正常的,因爲我認爲它應該。變量不可訪問
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class test {
public int charCountHelper(File handle, Character x) throws IOException {
int count = 0;
String data;
int index;
Character[] contents;
Scanner inputFile = new Scanner(handle);
while(inputFile.hasNext()){
data=inputFile.nextLine();
index = data.length()-1;
for(int i = 0; i< data.length(); i++){
contents = new Character[data.length()] ;
contents[i] = data.charAt(i);
}
count += charCount(contents,x,index);
}
inputFile.close();
return count;
}
public int charCount(Character[] content, Character x, int index) {
if(index < 0){
return 0; // this value represents the character count if the program reaches the beginning of the array and has not found a match.
}
if (content[index].equals(x)) {
return 1 + charCount(content, x, index - 1);
}
return charCount(content, x, index - 1); // this is the value that gets returned to the original calling method.
}
}
哪個變量? – Raedwald
count + = charCount(contents,x,index);內容變量。 – Keith