Lock1618
Lock1618

Reputation: 197

try and catch java

I have been making a GUI program and I am calling a method that throws an exception. I have to use a try and catch because i cannot edit the code because its GUI. For some reason the code just doesnt work. The code is supposed to get the first line of a file and display the number in a label. Here is the code:

    try{  
       String inputStr = JOptionPane.showInputDialog(this, "Enter The File Name: ");
       int x= codeReadFile(inputStr);
       String name= String.valueOf(x);
       chipCount.setText(name);
    }
    catch (IOException e) {
         JOptionPane.showMessageDialog(this,"No File");

    }    

the code for the filereading program is:

      public static int codeReadFile (String filename) throws IOException, 
      FileNotFoundException {
      String line=null;
      int value=0;
      BufferedReader inputReader = new BufferedReader (new 
            InputStreamReader(new FileInputStream(filename)));
            while (( line = inputReader.readLine()) != null)
                value = Integer.parseInt(line);
                inputReader.close();
                return value;

Upvotes: 0

Views: 750

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200138

You said you want to get the first line of the file, but this code obviously doesn't do that:

while (( line = inputReader.readLine()) != null)
  value = Integer.parseInt(line);

It tries to read the whole file and parse every line as an int, discarding all values but the last. What you probably wanted to say is

line = inputReader.readLine();
return line != null? Integer.parseInt(line) : 0;

You should have such code whether or not your file actually contains only one line. For example, if the file contains an extra line break, you'll read an empty line, try to parse it, and get a NumberFormatException.

Upvotes: 1

Zhedar
Zhedar

Reputation: 3510

GUI Operations should always be invoked on the EDT(Event Dispatch Thread). You can reach that by wrapping the modifying code into sth. like:

SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                chipCount.setText(name);
            }
        });

Otherwise ugly things may happen ;)

Then there's also an easier way to retrieve an BufferedReader. Simply drop the streams and use a FileReader instead.

The last thing is: If your file only contains one line, just read one. What you're doing is reading all lines. If the last one is empty, you're getting a wrong result or even a NumberFormatException by parseInt().

As another approach you could try to call repaint() or invalidate() on chipCount and/or its parent after you set the text. Edit: I just read you want to display that in a label... then repaint is definitively the way to go. You could also just use a JTextField and make it uneditable to get rid of this.

Upvotes: 0

Related Questions