我试图创建一个程序,让您选择一个文件,读取它然后将结果打印出来......这就是我到目前为止所拥有的
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”,我实际上对这些事情知之甚少..