Reputation: 594
I have tried to create a program that lets you to choose a file,reads it and then prints the results out... This is what i have so far
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;
}
And it runs okay,just doesn't do what it need to... How do I make "countChar" run? Because it doesn't print what i should..
I forgot to mention, if I call it after i print out the files name, I get this errro: "Unhandled exception type FileNotFoundException", I actually know really less about those things..
Upvotes: 0
Views: 1425
Reputation: 160
you just assign file name in FileName instead of file path. so you use this
if(returnVal==JFileChooser.APPROVE_OPTION) {
FileName=chooser.getSelectedFile().getAbsolutePath();
countChar();
because if file is in same directory where you project is then work but when selected file reside in different places then need to use absolutepath of selected file.
Upvotes: 0
Reputation: 8734
You're almost there! You're just printing out the filename instead of calling that method.
See this?
if(returnVal==JFileChooser.APPROVE_OPTION) {
FileName=chooser.getSelectedFile().getName();
System.out.println(FileName);
}
Instead of (or before or after, if you prefer) System.out.println(FileName);
, just put countChar();
.
Upvotes: 1