2014-10-11 12 views
-1

我正在編寫一個程序,允許我查看計算機上的java文件,並查看是否所有大括號匹配,因此在匹配{之前有{as}和no}個{}。它讓我選擇一個文件,然後在我做之後說我沒有這樣的元素異常,也沒有找到線。另一半它永遠運行,讓我覺得我設定了一個無限循環。任何與掃描儀或while循環的提示將不勝感激。我如何使用掃描儀有什麼問題?

public class BraceChecker { 

public static void main(String[] args) { 
    final JFileChooser fc = new JFileChooser(); 
    int response = fc.showOpenDialog(null); 
    boolean end = true; 

    if (response == JFileChooser.APPROVE_OPTION) { 
     File f = fc.getSelectedFile(); 
     Scanner scan1 = new Scanner(f.toString()); 
     String line; 
     ArrayListStack Stack1 = new ArrayListStack(); 
     while ((line = scan1.nextLine()) != null && end) { 
      for (int i = 0; i < line.length(); i++) { 
       if (line.charAt(i) == '{') { 
        Stack1.push('{'); 

       } 
       if (line.charAt(i) == '}') { 
        if (Stack1.isEmpty()) { 
         System.out.println("Braces Are Unbalanced"); 
         end = false; 
         i = line.length(); 
        } else { 
         Stack1.pop(); 
        } 
       } 
      } 
     } 
     if (end == true && Stack1.isEmpty()) { 
      System.out.println("Braces are Balanced"); 
     } 

    } 

} 
+0

你有沒有通過該計劃一步一個調試器,而它的處理有問題的文件中的一個?如果沒有,那可能是一個開始的好地方。 – 2014-10-11 19:34:45

+0

但是當它說線沒有找到時呢? – trosy 2014-10-11 19:35:33

回答

1

這是你的問題:

while ((line = scan1.nextLine()) != null && end) 

使用掃描儀的hasNextLine方法來代替。 nextLine拋出一個NoSuchElement如果您嘗試掃描行不存在(即,如果你試圖去關文件的末尾)

0

我看到在這2個問題:

Scanner scan1 = new Scanner(f.toString()); 

的掃描程序應掃描文件不是它的字符串表示,否則它會從f.toString() litterally掃描該字符串,這將是該文件的名稱,所以使用:

new Scanner(f);// the file itself not its String representation 

然後對NoSuchElement錯誤。這是您爲while循環編寫的條件的問題。雖然把!= null看起來是正確的,但如果行不在那裏,scanner.nextLine()不會返回null,它會拋出一個NoSuchElementException異常。

因此,要解決這個問題的嘗試:

String line ; 
while(scanner1.hasNext()){ //hasNext() means the sanner has a next line 
    line = scanner1.nextLine(); 
}