2012-09-27 1 views
0

CCE를 해결하는 데 문제가 있습니다. 이 과제들은 일치하거나 (예를 들어, ACC 또는 REJ)와 일치하지 않는 경우 결정하기 위해 특정 정규 표현식에에 구문 분석 배경을 런타임에 .txt 파일을 연 다음 컴파일러 을 가지고 사용자에 대한 호출하지만 캐치입니다 그 사용자는 JFileChooser로 파일을 열어야 만합니다. 나는이를 게시하기 전에 많은 독서와 연구를했는데 문제는 내가 이해 JFileChooser로는, java.io.File의 자체를 사용하는 것 같다 만 스캐너이있는 .txt 파일의 입력을 구문 분석 할 수 있도록 보인다 대본. 내가 파일 에서 텍스트의 모든 라인을 읽을 전적으로 스캐너를 사용하는 경우JFileChooser 및 .txt 파일 구문 분석 문제가 발생했습니다.

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/class-use/File.html

그래서,이 '컴파일'를 제외한 모든 콘솔 출력을 보여 주었다 것은 예를 들어, "널 널 널 널 널 (null)"이었다 (예 : 파일에 5 줄의 텍스트가있는 경우). 이 예에서는 별도의 라인

S에 인쇄 된 각 규칙 있어야 EDIT : 편의상 다음은 (속기 위하여 또는 ACC) 상 허용 간주 될 .txt 파일의 예 AB A : 0A A : 전자 B : 1B B : 전자 내 소스 코드를 제공 한

. charSequences는 Scanner/BR이 파싱해야하는 정규식입니다 ( ). 또한 주어진 줄이 거부되는 경우 (REJ, 축약어로 ), 사용자에게 즉시 경고해야합니다. 분명히 나는이 수업을 이해할 수 없을뿐만 아니라 ... 내가 필요하다고 생각했을 수도 있습니다. FileReader와 같은 것을 사용하고 나는 기초부터 벗어나는 방법이지만, 단지 은 일반적으로 Java 입출력의 복잡성에 좌절감을 느낍니다. 나는이 모든 노력과 노력을 기울이기 때문에 드물게 보여줄 것이 거의 없다.

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.Reader; 
import java.util.*; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
import javax.swing.JFileChooser; 
import javax.swing.JOptionPane; 

public class Simplified 
{ 


public Simplified() throws Exception 
{ 
    readLines(); 
} 

public void readLines() throws Exception 
{ 

    //MUST prompt user to use JFileChooser 
    JFileChooser ranFi = new JFileChooser(); 
    //approve condition 
    if(ranFi.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) 
    { 
     //get selected file 
     Comparable<File> file = ranFi.getSelectedFile(); 
     //create a bufferedReader for the file 
     //BufferedReader br = new BufferedReader((Reader) file); 
     BufferedReader br = null; 

     //create local String object the refer to file's current line 
     String currentLine; 

     /************************** 
     * Length(LHS,RHS) = 1,1 
     * --CharSequence compilations 
     * ****************************** 
     */ 
     //ACC 
     CharSequence fp100 = "[S][:][A-Ze0-1]"; 
     //ACC iff is NOT the very first line of text file 
     CharSequence fp101 = "[A-Z&&[^S]][:][A-Ze0-1]"; 


     /************************** 
     * Length(LHS,RHS) = 1,2 
     * --CharSequence compilations 
     * ****************************** 
     */ 
     //ACC 
     CharSequence fp200 = "[S][:][A-Z0-1][A-Z0-1]"; 
     //ACC iff is NOT the very first line of text file 
     CharSequence fp201 = "[A-Z&&[^S]][:][A-Z0-1][A-Z0-1]"; 

     /************************** 
     * Length(LHS,RHS) = 1,3 
     * --CharSequence compilations 
     * ****************************** 
     */ 
     //ACC 
     CharSequence fp300 = "[S][:][A-Z0-1][A-Z0-1][A-Z0-1]"; 
     //ACC iff is NOT the very first line of text file 
     CharSequence fp301 = "[A-Z&&[^S]][:][A-Z0-1][A-Z0-1][A-Z0-1]"; 

     /** 
     * Length(LHS,RHS) = 1,4 
     * --CharSequence compilations 
     * ****************************** 
     */ 

     //REJ 
     CharSequence fp400 = "[.][.][.][.][.][.]"; 


     //create a Scanner for the file 
     Scanner text = new Scanner((Readable) file); 

     try 
     { 
      br = new BufferedReader((Reader) file); 
      //while there are still lines to be read in the file 
      //where currentLine = present line of the bufferedReader 
      while((currentLine = br.readLine()) != null) 
      { 

       //while the scanner still has lines to read in the file 
       while(text.hasNext()) 
       { 


       //to remove trailing whitespace in the file, starting 
       //@ the first line in the text file... 
       String trimStartLine = currentLine.trim(); 

       //ALL feasible ACC permutations for starting line 
       if(trimStartLine.contains(fp100)||trimStartLine.contains(fp200)||trimStartLine.contains(fp300)) 
       { 
        System.out.println("first line valid..."); 


       } 
       //ALL feasible REJ permutations for starting line 
       else if(!trimStartLine.contains(fp100)||!trimStartLine.contains(fp200)||!trimStartLine.contains(fp300)) 
       { 
        System.out.println("invalid first line..." + 
          "...terminating"); 
        System.exit(0); 
       } 

       //once again removing trailing whitespace in the file, 
       //this time trimming the whitespace in the second line 
       //of the file, provided that iff the first line of the 
       //file was valid to begin with... 
       String trim2ndLine = currentLine.trim(); 

       //permutations have now increased to 6 since "[S]" isn't 
       //technically required for ANY line other than the first line 
       if(trim2ndLine.contains(fp100)||trim2ndLine.contains(fp101)||trim2ndLine.contains(fp200)|| 
         trim2ndLine.contains(fp201)||trim2ndLine.contains(fp300)||trim2ndLine.contains(fp301)) 
       { 
        System.out.println("2nd line valid..."); 

        //only included two line checks for now... 
        //as of now if the first two lines are valid 
        //then print out the remaining lines in the 
        //file... 
        System.out.println(text.nextLine()); 

       } 
       else if(!trim2ndLine.contains(fp100)||!trim2ndLine.contains(fp101)||!trim2ndLine.contains(fp200)|| 
         !trim2ndLine.contains(fp201)||!trim2ndLine.contains(fp300)||!trim2ndLine.contains(fp301)) 
       { 
        System.out.println("invalid 2nd line..." + 
          "...terminating"); 
        System.exit(0); 
       } 
       else 
       { 
        System.out.println("no file was selected"); 
       } 

      }//end of inner while 
      }//end of outer while 
     }//end of try 
       catch (Exception ex) 
       { 
        System.out.println(ex.getMessage()); 
       } 
       finally 
       { 
        try 
        { //close text while lines remain, 
         //valid or not... 
         if(br != null && text != null){ 
          br.close(); 
          text.close(); 
         } 
        } 
        catch (Exception ex) 
        { 
        } 
       }//end of finally 
     System.out.println("end of file successfully reached..."); 
    }//end of approve option 
}//end of method 




public static void main(String[] args) throws Exception 
{ 
    Simplified mn = new Simplified(); 
    mn.readLines(); 
}//end of main 

}//end of Simplified.java 

결론에 상관없이 소스 코드도 내 스캐너와의 BufferedReader 객체의 타입 캐스팅에 배치, 나는 항상 CCE를 얻고 있다는 것입니다. 어떤 도움이라도 엄청날 것입니다. 미리 감사드립니다.

+0

여기에 스택 추적을 붙일 수 있습니까 – Michael

+0

@ Michael hello there. 스택 추적은 다음과 같습니다. Thread [main] (일시 중지됨 (예외 ClassCastException)) Simplified.readLines() 줄 : 83 간체. () 줄 : 21 Simplified.main (String []) 줄 : 179 – OcelotXL

답변

1
  1. JFileChooser.getSelectedFile은 왜위한 Comparable<File>에 포장하려는 나도 몰라하는 File 반환 ?? 파일 자체는 Comparable을 구현합니다.
  2. Scanner은 입력으로 File을 허용합니다. 나는 Scanner API 경험이 아니에요 동안, 나는 당신이 소스 실행 얻을 충분해야한다으로 단순히 FileScanner를 창조하는 BufferedReader 필요하다고 생각하지 않습니다.

그는 당신이 시도 할 수있는 간단한 테스트입니다.

  1. 테스트 할 내용이 담긴 간단한 텍스트 파일을 만듭니다.
  2. public static void main(String args[]) {...} 메서드가있는 Class을 간단하게 만듭니다.main 방법에서

Scanner scanner = new Scanner(new File("path/to/text/file/text.txt")); 
while (scanner.hasNext()) { 
    System.out.println(scanner.next()); 
} 

는 거기에서 파싱 로직에 추가하기 시작 ... 뭔가를하려고합니다.

+0

ok 멋진 콩 나는 그것을 나중에 오늘 여기에서 시험해 볼 것이다. thx man – OcelotXL

관련 문제