| | |
PLS Help newbie
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Jan 2005
Posts: 2
Reputation:
Solved Threads: 0
How can i add reversing line code to the following code. Program must read the document which is selected by user from filechooser and write the reverse lines to another file. Additionally, I have to add a histogram which shows the length of each lines in document.
Java Syntax (Toggle Plain Text)
import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; import java.text.*; public class WordAnalyser extends JFrame implements ActionListener { // Menu items Open, Clear, Exit, WordCount, About private JMenuItem jmiOpen, jmiClear, jmiExit, jmiWordCount, jmiAbout; // Text area for displaying and editing text files private JTextArea jta1, jta2; // Status label for displaying operation status private JLabel jlblStatus; // File dialog box private JFileChooser jFileChooser = new JFileChooser(); File infile; File outfile = new File("OutFile.txt"); DecimalFormat numForm1 = new DecimalFormat("000"); DecimalFormat numForm2 = new DecimalFormat("0.00"); // Main method public static void main(String[] args) { WordAnalyser frame = new WordAnalyser(); frame.setSize(500, 400); frame.center(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public WordAnalyser() { setTitle("Word Analyser"); // Create a menu bar mb and attach to the frame JMenuBar mb = new JMenuBar(); setJMenuBar(mb); // Add a "File" menu in mb JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); mb.add(fileMenu); // Add a "Help" menu in mb JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); mb.add(helpMenu); // Create and add menu items to the menu fileMenu.add(jmiOpen = new JMenuItem("Open", 'O')); fileMenu.add(jmiClear = new JMenuItem("Clear", 'C')); fileMenu.addSeparator(); fileMenu.add(jmiExit = new JMenuItem("Exit", 'E')); helpMenu.add(jmiWordCount = new JMenuItem("Word Count", 'W')); helpMenu.add(jmiAbout = new JMenuItem("About", 'A')); // Set default directory to the current directory jFileChooser.setCurrentDirectory(new File(".")); // Set BorderLayout for the frame getContentPane().add(new JScrollPane(jta1 = new JTextArea()), BorderLayout.CENTER); getContentPane().add(jta2 = new JTextArea(), BorderLayout.EAST); getContentPane().add(jlblStatus = new JLabel(), BorderLayout.SOUTH); // Register listeners jmiOpen.addActionListener(this); jmiClear.addActionListener(this); jmiExit.addActionListener(this); jmiWordCount.addActionListener(this); jmiAbout.addActionListener(this); } public void center() { // Get the screen dimension Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; // Get the frame dimension Dimension frameSize = this.getSize(); int x = (screenWidth - frameSize.width)/2; int y = (screenHeight - frameSize.height)/2; // Determine the location of the left corner of the frame if (x < 0) { x = 0; frameSize.width = screenWidth; } if (y < 0) { y = 0; frameSize.height = screenHeight; } // Set the frame to the specified location this.setLocation(x, y); } // Handle ActionEvent for menu items public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (e.getSource() instanceof JMenuItem) { if ("Open".equals(actionCommand)) open(); else if ("Clear".equals(actionCommand)) clear(); else if ("Exit".equals(actionCommand)) System.exit(0); else if ("Word Count".equals(actionCommand)) word_count(); else if ("About".equals(actionCommand)) JOptionPane.showMessageDialog(this, "Program performs text analysis", "About This Program", JOptionPane.INFORMATION_MESSAGE); } } // Open file private void open() { if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { infile = jFileChooser.getSelectedFile(); open(infile); } } // Open file with the specified File instance private void open(File file) { try { // Read from the specified file and store it in jta BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); byte[] b = new byte[in.available()]; in.read(b, 0, b.length); jta1.append(new String(b, 0, b.length)); in.close(); // Display the status of the Open file operation in jlblStatus jlblStatus.setText(file.getName() + " Opened"); } catch (IOException ex) { jlblStatus.setText("Error opening " + file.getName()); } } // Clear all display areas private void clear() { jta1.setText(""); jta2.setText(""); jlblStatus.setText(""); } // Perform word analysis with specified File instance private void word_count() { int buff; // for reading 1 char at a time int count = 0; int sentences = 0; int words = 0; int chars = 0; boolean start = true; try { FileInputStream instream = new FileInputStream(infile); FileOutputStream outstream = new FileOutputStream(outfile); // convert FileOutputSream object to PrintStream object for easier output PrintStream out = new PrintStream(outstream); out.println("---Word Analysis---"); while ((buff=instream.read()) != -1) { switch((char)buff) { case '?': case '.': case '!': { if (start == false) { sentences++; words++; start = true; } break; } case ' ': case '\t': case '\n': case ',': case ';': case ':': case'\"': case'\'': { if (start == false) { words++; start = true; } break; } default: { // 3-digit integer format if (((char)buff >= 'a' && (char)buff<='z')|| ((char)buff >= 'A' && (char)buff<='Z')|| ((char)buff >= '0' && (char)buff <= '9')|| ((char)buff == '-')) { chars++; if ((words % 50) == 49) { if (start == true) { out.println(); out.print(numForm1.format(words+1) + " "); } out.print((char)buff); } start = false; } } }// switch }//while instream.close(); out.println(); out.println(); out.println("Number of characters: " + chars); out.println("Number of words: " + words); out.println("Number of sentences: " + sentences); out.print("Number of words per sentence: "); // cast integers to float, then add 0.005 to round up to 2 decimal places out.println(numForm2.format((float)words/sentences)); outstream.close(); try { //Read from the output file and display in jta BufferedInputStream in = new BufferedInputStream(new FileInputStream(outfile)); byte[] b = new byte[in.available()]; in.read(b, 0, b.length); jta2.append(new String(b, 0, b.length)); in.close(); } catch (IOException ex) { jlblStatus.setText("Error opening " + outfile.getName()); } } catch (Exception e) { System.out.println(e); } } }
Last edited by alc6379; Jan 3rd, 2005 at 5:56 pm. Reason: added [code] tags
•
•
Join Date: Jun 2004
Posts: 609
Reputation:
Solved Threads: 8
Hi everyone,
Use the getText() in the text area and get the length of the string. After that convert the string into a chars array and then reverse the char array adding the reversed chars to it(see the StringBuffer Class). After that set the text into the text area. as for the histogram it is not something easy and its quite hard to accomplish so i would advice you to get an open source third party graphing library.
I hope this helps you
Yours Sincerely
Richard West
Use the getText() in the text area and get the length of the string. After that convert the string into a chars array and then reverse the char array adding the reversed chars to it(see the StringBuffer Class). After that set the text into the text area. as for the histogram it is not something easy and its quite hard to accomplish so i would advice you to get an open source third party graphing library.
I hope this helps you
Yours Sincerely
Richard West
![]() |
Similar Threads
Other Threads in the Java Forum
- Previous Thread: Document.insertString(); not working
- Next Thread: get cursor position in a JTextArea
Views: 3023 | Replies: 1
| Thread Tools | Search this Thread |
Tag cloud for Java
3d @param affinetransform android api apple applet application arc arguments array arrays automation binary bluetooth byte c# chat class classes click client code compare component corrupted database detection draw eclipse error event exception file fractal game givemetehcodez graphics gui guitesting helpwithhomework html ide image input integer j2me java java.xls javaprojects jmf jni jpanel julia keytool linux list loop map method methods mobile netbeans newbie number object oracle os pong print problem producer program programming project projectideas read recursion reflection replaysolutions rim scanner screen server set size sms socket sort sql string swing terminal test threads time transfer tree web windows





