2016-01-23 100 views
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. 

    } 
} 
+0

哪个变量? – Raedwald

+0

count + = charCount(contents,x,index);内容变量。 – Keith

回答

3

在你的代码,contents不会,如果data.length()等于0的循环是在任何情况下不正确初始化contents,因为如果你这样做的,它只会包含指定一个字符初始化在循环的最新初始化期间。只需将循环上方的行初始化为contents即可。

+0

这似乎解决了这个问题。谢谢。 – Keith