2012-01-29 2 views
1

스택 데이터 구조 사용 : 입력 파일의 균형이 맞지 않으면 언밸런스 원인과 파일 내 현지화 세부 정보가 제공됩니다. 유연성을 위해 텍스트 파일에서 균형 잡힌 기호 쌍을 읽으십시오. 기호 다음 쌍을 고려하여 프로그램을 테스트합니다} {(), [],/* */기호 쌍 Java 프로그램

내가 마지막 요구 사항에 문제가있어/* */

I 수도 있습니다 ' 파일 내 로컬 리 제이션 세부 사항을 인쇄하는 방법을 파악하고있는 것 같습니까? 오류가 발생한 텍스트 파일의 줄 번호는 무엇입니까?

은 텍스트 파일은 다음과 같습니다

(()(() 
{}}}{}{ 
[[[]][][] 
((}})){{] 
() 
[] 
{} 
[]{} 
()()()[] 
*/ /* 
(a+b) = c 

코드 :

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 


public class P1 { 

    private boolean match = true; 

    // The stack 
    private java.util.Stack<Character> matchStack = new java.util.Stack<Character>(); 

    // What to do with a match 
    public boolean ismatch() { 
     return match && matchStack.isEmpty(); 
    } 

    // Finding a match 
    public void add(char c) { 
     Character k = leftSide(c); 

     if (k == null) 
      ; 
     else if (k.charValue() == c) 
      matchStack.push(k); 
     else { 
      if (matchStack.isEmpty() || !matchStack.pop().equals(k)) 
       match = false; 
     } 
    } 

    // Add string values 
    public void add(String s) { 
     for (int i = 0; i < s.length(); i++) 
      add(s.charAt(i)); 
    } 

    // The various symbol pairs 
    protected static Character leftSide(char c) { 
     switch (c) { 
     case '(': 
     case ')': 
      return new Character('('); 
     case '[': 
     case ']': 
      return new Character('['); 
     case '{': 
     case '}': 
      return new Character('{'); 
     default: 
      return null; 
     } 
    } 

    // Main method. Welcome message, read the test file, build the array, print 
    // results. 
    public static void main(String args[]) { 

     List<String[]> arrays = new ArrayList<String[]>(); 

     // Welcome message 
     System.out 
       .println("Project #1\n" 
         + "Welcome! The following program ensures both elements of various paired symbols are present.\n" 
         + "Test Data will appear below: \n" 
         + "-------------------------------"); 

     // Read the file 
     try { 
      BufferedReader in = new BufferedReader(new FileReader(
        "testfile.txt")); 
      String str; 

      // Keep reading while there is still more data 
      while ((str = in.readLine()) != null) { 

       // Line by line read & add to array 
       String arr[] = str.split(" "); 
       if (arr.length > 0) 
        arrays.add(arr); 

       // Let the user know the match status (i.e. print the results) 
       P1 mp = new P1(); 
       mp.add(str); 

       System.out.print(mp.ismatch() ? "\nSuccessful Match:\n" 
         : "\nThis match is not complete:\n"); 
       System.out.println(str); 
      } 
      in.close(); 
      // Catch exceptions 
     } catch (FileNotFoundException e) { 
      System.out 
        .println("We're sorry, we are unable to find that file: \n" 
          + e.getMessage()); 
     } catch (IOException e) { 
      System.out 
        .println("We're sorry, we are unable to read that file: \n" 
          + e.getMessage()); 
     } 

    } 

    } 

답변

0

쉬운 방법이 같은 Location 클래스가 Map<String, Stack<Location>>, 같은 스택의지도를 사용하는 것입니다 구현 int (행 번호와 문자 번호)이 두 개 들어 있습니다. 그게 네 위치 정보가 될 수있어. 이지도의 키 (String)는 페어의 왼쪽 (오프너) 부분입니다. 당신이 오프너를 가질 때마다지도에서 적절한 Stack을 찾아 그 오프너를 위해 새로운 Location을 밉니다. 더 가까울 때마다 오프너를 들여다보고, 오프너를 사용하여지도에서 올바른 Stack을 찾은 다음 한 번 튕겨냅니다. 내가 귀하의 키에 String을 사용하는 이유는 오프너를 모두 Character/* 개개전으로 표시 할 수있는 것은 아니기 때문에 String이 필요합니다. leftSide(char) (현재는 leftSide(String)) 기능으로 문자열을 사용할 수 없으므로 if-else을 사용해야하거나지도 (Map<String, String>)를 사용하여 더 가까운 오프너 매핑을 만들 수 있습니다.

파일의 끝에 도달하면 개체에 남아있는 유일한 Location 개체 만 닫히지 않은 오프너 여야합니다.

+0

답변에 너무 중요하지 않지만 실제로 [JDK 7] (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)에서 문자열을 바꿀 수 있습니다.). – Mac