2015-11-06 70 views
0

我创建了一个程序来匹配两个txt文件。我得到的编译错误,标志从未初始化,但我不知道为什么。 for循环应该运行,if if应该初始化标志。任何帮助,将不胜感激。谢谢!国旗从未初始化

public static void main(String[] args) throws IOException 
{ 
    boolean flag; 
    File f = new File(args[0]); 
    Scanner sc = new Scanner(f); 
    File f2 = new File(args[1]); 
    Scanner sc2 = new Scanner(f2); 
    int line = 1; 
    String t1 = ""; 
    String t2 = ""; 

    while(sc.hasNextLine() && sc2.hasNextLine()) 
    { 
     String line1 = sc.nextLine().toUpperCase(); 
     String line2 = sc2.nextLine().toUpperCase(); 

     for(int i = 0; i < line; i++) 
     { 
      if(line1.substring(0,i).equals(line2.substring(0,i))) 
      { 
       flag = false; 
       t1 = line1.substring(0,i); 
       t2 = line2.substring(0,i); 
       System.out.print(""); 
      } 
      else 
      { 
       flag = true; 
       t1 = line1.substring(0,i); 
       t2 = line2.substring(0,i); 
       System.out.print(""); 
      } 
     } 

     if(flag == true) 
     { 
      System.out.println("Line # " + line + ": Matching " + line + "character/s true" + "**" + t1 + "**" + t1 + "**"); 

     } 
     else 
     { 
      System.out.println("Line # " + line + ": Matching " + line + "character/s false" + "**" + t1 + "**" + t2 + "**"); 
     } 
     line += 1; 
    } 
} 

}

+0

如果您的'for'循环从未运行会怎么样?那么'flag'的价值是什么? –

回答

0

在你的主函数的顶部,它抱怨,因为这行:

boolean flag; 

需要初始化这个变量。什么是默认行为?如果for循环从不运行,值会是什么?

例如,如果你传递函数两个空文件(或一个空文件)?然后,你的while循环:

while(sc.hasNextLine() && sc2.hasNextLine()) 

将是错误的,并且该标志永远不会被设置。这就是编译器抱怨的原因。