2013-05-20 135 views
0

我试图创建一个程序,让你选择一个文件,读取它,然后将结果打印出来后读取文件...这是我迄今为止按下一个按钮

public class Main { 
    public static void main(String[] args) { 
     JFrame frame = new JFrame("Bebras braces matcher"); 
     JButton selectf = new JButton("Open file"); 
     selectf.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       String cmd = e.getActionCommand(); 
       if(cmd.equals("Open file")) { 
        JFileChooser chooser =new JFileChooser(); 
        FileFilter filefilter = new FileNameExtensionFilter("","txt"); 
        chooser.setFileFilter(filefilter); 
        int returnVal = chooser.showOpenDialog(chooser); 
        if(returnVal==JFileChooser.APPROVE_OPTION) { 
         FileName=chooser.getSelectedFile().getName(); 
         System.out.println(FileName);  
        } 
       } 
      } 
     }); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(500,500); 
     frame.add(selectf); 
     frame.setVisible(true); 

    } 
    public static void countChar() throws FileNotFoundException { 
     Scanner scan = null; 
     try { 
      scan = new Scanner(new File(FileName)); 
     } 
     catch (FileNotFoundException e) { 
     } 
     while (scan.hasNext()) { 
      String character = scan.next(); 
      int index =0; 
      char close = '}'; 
      char open = '{'; 
      while(index<character.length()) { 

       if(character.charAt(index)==close){ 
        CloseCount++; 
       } 
       else if(character.charAt(index)==open) { 
        OpenCount++; 
       } 
       index++; 
      } 
     } 
     System.out.println("Opened: "+OpenCount+"Closed: "+CloseCount); 
    } 
    private static String FileName; 
    private static int CloseCount = 0; 
    private static int OpenCount = 0; 
    private static final long serialVersionUID = 7526472295622776147L; 
} 

它运行良好,只是没有做它需要...我如何使“countChar”运行?因为它不打印我应该打印什么..

我忘了提及,如果我打印出文件名后打电话给它,我得到这个错误:“未处理的异常类型FileNotFoundException”,我其实知道的真的不多那些东西..

+2

那么,countChar应该做什么? –

+0

你在哪里叫它? – hoaz

回答

1

你几乎在那里!您只是打印出文件名而不是调用该方法。

看到这个?

if(returnVal==JFileChooser.APPROVE_OPTION) { 
    FileName=chooser.getSelectedFile().getName(); 
    System.out.println(FileName);  
} 

代替(或前或后,如果您愿意)System.out.println(FileName);,只是把countChar();

+0

虽然,静态字段应该由局部变量和参数替换。 –

+0

当然,还有其他一些风格问题。但是他们今天超出我们的范围。这就是问题的答案。 – Etaoin

+0

我忘了说我试过了。我得到一个错误:“未处理的异常类型FileNotFoundException”..就像我无法找到,因为用户指定它! – Bebras

0

您只需在文件名中指定文件名而不是文件路径。 所以你用这个

if(returnVal==JFileChooser.APPROVE_OPTION) { 
FileName=chooser.getSelectedFile().getAbsolutePath(); 
countChar(); 

,因为如果文件是在你的项目,然后工作,但选择文件时,在不同地方居住同一个目录,然后需要使用absolutepath选择的文件。