Results 1 to 6 of 6
  1. #1
    USMCstitch is offline Member
    Join Date
    Aug 2010
    Posts
    6
    Rep Power
    0

    Default Explanation of problem and/or alternative solution

    I've got this homework problem, that while solved, I don't understand certain parts, specifically the "meat" of the whole program. I was working with a friend, and he helped me over this hurdle, basically "here, use this", but I don't understand why he did what he did. I can't ask him, as he is in Iraq and his unit got sent out, and i'm not sure when he'll return.

    The problem is to display a histogram panel in a frame, that gets its data from a file called from a text field. The instructions also state that pressing the Enter key on the text field will cause the program to run and display in the histogram.

    1. can someone explain to me the actionPerformed part? I don't get it starting with the "while" in the try and the "finally" section.

    2. I don't see a keyPressed event in this code to register the Enter key being pressed, yet it works.



    I've tried modifying the code to make it...simpler...but whatever i do, i can't get to work. Since i don't understand it, I can't turn it in as mine. I tried finding information on FileReader, but everything i try doesn't work either.

    Can someone please explain the above?

    Java Code:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    
    public class Exercise_Histogram extends JFrame implements ActionListener {
     
    	int count[] = new int[26];
    	private JTextField fileName = new JTextField(20);
    	private Histogram histogram = new Histogram();
    
    	public Exercise_Histogram() {
       
    		JPanel p = new JPanel();
       		p.setLayout(new BorderLayout());
      		p.add(new JLabel("Text File"), BorderLayout.WEST);
       		p.add(fileName, BorderLayout.CENTER);
    
       		setLayout(new BorderLayout());
       		add(p, BorderLayout.SOUTH);
       		add(histogram, BorderLayout.CENTER);
    
       		fileName.addActionListener(this);
    	}
    
    	public void actionPerformed(ActionEvent e) {
    		FileReader f = null;
    		int r = 0;
    		for (int i = 0; i < 26; i++) {
    			count[i] = 0;
    		}
    
    		try {
    			f = new FileReader(new File(fileName.getText().trim()));
    			
    			while ((r = f.read()) != -1) {
    				if ((r >= 65) && (r<=90)) {
    					count[r-65]++;
    				}
    					else if ((r >= 97) && (r<=122)) {
    						count[r-97]++;
    					}
    			}
    		}
    		catch (FileNotFoundException ex) {
    			System.out.println("File not found: " + fileName.getText().trim());
    		}
    		catch (IOException ex) {
    			System.out.println(ex.getMessage());
    		}
    		finally {
    			try {
    				if (f != null) f.close();
    			}
    			catch (IOException ex) {}
    		}
    
    		histogram.showHistogram(count);
    	}
      
    	public static void main(String[] args) {
    	   Exercise_Histogram frame = new Exercise_Histogram();
    	    frame.setTitle("Exercise_Histogram");
    	    frame.setSize(400, 300);
    	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    frame.setLocationRelativeTo(null); // Center the frame
    	    frame.setVisible(true);
    	}
    }

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I'll do my best to explain everything to you, and hopefully any bad advice will be caught by others. I believe if you add an action listener to a JTextField, hitting enter fires an ActionEvent(same as when you click a button), if you wanted you could add a button and have it use the same actionPerformed method. When you click the button it would do the same thing as hitting enter on your keyboard.

    Ill go over the next few things a piece at a time. Since you are opening a fileReader you must wrap it in a try catch block. It has a chance of throwing an exception and you must be ready to handle that exception. With a try catch block, it tries to do something risky and it's prepared to catch any errors that might occur. In this case, a non existent file or an IOException.

    It has a while loop since it is reading from a file, it will keep reading the file until the file is finished, each step it reads in a character(this part could be wrong, I don't usually use just a filereader)

    It appears to be counting the occurrence of certain letters in a text file. Each step through the loop gets some integer which represents an ASCII number(check an ascii chart for which numbers represent letters. From there it is incrementing the correct index. Im assuming it's counting letters, in the count array, 0 would be a, 1 would be b, etc.

    Last, the finally clause is there to guarantee that the file reader is closed. It wraps the lines in another try/catch block for the same reasons as above.

    Here are some useful links:
    http://download.oracle.com/javase/6/...ileReader.html
    http://www.asciitable.com/
    http://download.oracle.com/javase/tu...al/exceptions/

    Java Code:
    read
    
    public int read()
             throws IOException
    
        Reads a single character.
    
        Overrides:
            read in class Reader
    
        Returns:
            The character read, or -1 if the end of the stream has been reached 
        Throws:
            IOException - If an I/O error occurs
    This is the description of the read method you are using.

    So each step stores an integer(character) from the file, if it is -1, the loop stops because the file is done. Then it does tests on that number if it isn't -1.

    More details:
    65 is a capital A, 90 is a capital Z
    97 is a lower case a, 122 is a lowercase z

    I hope I have cleared everything up for you. If anything is unclear, please ask.
    Last edited by sunde887; 04-19-2011 at 04:02 AM.

  3. #3
    USMCstitch is offline Member
    Join Date
    Aug 2010
    Posts
    6
    Rep Power
    0

    Default

    Actually, the more details you provided made the light bulb go off. I can now read that while loop. I was studying that oracle FileReader link adnausum, but i didn't even think about the ASCII set. It was really just the while loop throwing me for an exception...i mean loop. :p

    Thank you for explaining that too me.

    one more question: Why is it when i take out that while loop, the "enter" key doesn't execute?

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Are you sure it doesn't? It seems like it is, you just don't notice because it doesn't produce visible results. Try replacing the while loop with something like this
    Java Code:
    System.out.println("HI");
    and see if that's printed to the console when you hit enter.

  5. #5
    USMCstitch is offline Member
    Join Date
    Aug 2010
    Posts
    6
    Rep Power
    0

    Default

    Ohhhh...ok.

    I see, it does print, but since i took out the while, its not counting the characters in the text file, thereby not incrementing count and as a result, returning null/0 in the histogram.

    Thank you very much for your help!

  6. #6
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You are welcome. I'm glad to have helped you understand, and I hope I was clear.

    Please mark your thread solved with the thread tools at the top if you are satisfied with the explanations I have given you.

Similar Threads

  1. Replies: 5
    Last Post: 02-23-2011, 10:14 PM
  2. Need smart solution on java game lag problem..
    By Addez in forum New To Java
    Replies: 0
    Last Post: 11-13-2009, 01:48 PM
  3. Ajax's confusion code problem perfect solution
    By chinafhf in forum Web Frameworks
    Replies: 0
    Last Post: 03-16-2009, 02:56 PM
  4. Replies: 0
    Last Post: 02-24-2009, 03:40 PM
  5. Any Alternative to Swing?
    By Niveditha in forum AWT / Swing
    Replies: 13
    Last Post: 06-27-2008, 10:39 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •