Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: Reading from a sequential file to an array

  1. #1
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Reading from a sequential file to an array

    I am having trouble figuring out what I want to do, and the idea seems like it would be simple. I have four lines in a text file, they are strings and include "7 years at 5.35%", "10 years at 5%", "20 years at 5.65%", "30 years at 5.75%". I need to pull these strings from a text file and enter them into an array. I currently have the strings I used initialized straight into an array and I do not want to redo more of the code than needed. I currently have

      1 package week4;  //indicates this file belongs to a package named week4
      2 
      3 /**
      4  *
      5  * @author Chad McCoy
      6  */
      7 
      8 import java.awt.*; //these import everything needed for use in program
      9 import java.text.NumberFormat;
     10 import java.awt.event.ActionEvent;
     11 import java.awt.event.ActionListener;
     12 import javax.swing.*;
     13 import static java.lang.Math.*;
     14 import javax.swing.JTextArea;
     15 import javax.swing.JScrollPane; 
     16 
     17 
     18 public class MortgageCalc1 extends JFrame {  //class definition
     19     GridBagConstraints gbc = new GridBagConstraints();
     20     private void set_gbc(int row, int column, int width, int height, int fill, int v, int h) {
     21                    gbc.gridy = row;
     22                    gbc.gridx = column;
     23                    gbc.gridwidth = width;
     24                    gbc.gridheight = height;
     25                    gbc.fill = fill;
     26                    gbc.ipady = v;
     27                    gbc.ipadx = h;
     28 
     29                 }
     30     
     31     JLabel firstNumLabel = new JLabel("Mortgage Principal:"); //this section establishes variables
     32     JTextField firstNumField = new JTextField("0");
     33     
     34     JLabel resultLabel = new JLabel("Payment Amount:");
     35     JTextField resultField = new JTextField("0");
     36     
     37     JLabel comboOptions = new JLabel("Term Options, must click one");
     38     
     39     JButton calcButton = new JButton("Calculate Payment");
     40     JButton closeButton = new JButton("Close");
     41     JButton resetButton = new JButton("Reset Calculator");
     42     JButton startOvrButton = new JButton("Start Over");
     43     
     44     public int pymtAmt = 0;
     45     public double intRate = 0;
     46     public int monMorTerms = 0;
     47     
     48     String[] loanTerms = { "7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%" };
     49     JComboBox mortgageTerms = new JComboBox(loanTerms);
     50     
     51     JTextArea outputArea = new JTextArea();
     52     JScrollPane scrollPane = new JScrollPane(outputArea);
     53     
     54     JTextArea headingArea = new JTextArea();
     55     JScrollPane scrollPane2 = new JScrollPane(headingArea);
     56     
     57     private final static String newLine = "\n";
     58     
     59     String addLine2 = ("Pmt#" + "\t" + "Pmt Amt" + "\t" + "Loan Bal" + "\t" + "Int Paid");
     60                             
     61                             
     62                             
     63     public MortgageCalc1() {  //constructor for the class
     64         super("Mortgage Calculator"); //this makes a title for the window
     65         setLocation(500, 200); //this sets the location of the window
     66         setSize (360,500); //sets the window size
     67         setResizable(true); //allows user to resize window
     68         this.setDefaultCloseOperation(EXIT_ON_CLOSE); //this states the program will end when the window is closed
     69         setLayout(new GridBagLayout()); //defines window layout
     70 
     71                 
     72         set_gbc(0, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10); //establishes contraints for gridbag
     73         add(firstNumLabel,gbc); //these lines add the elements to the window
     74         set_gbc(0, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     75         add(firstNumField,gbc);
     76         set_gbc(1, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     77         add(comboOptions,gbc);
     78         set_gbc(1, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     79         add(mortgageTerms,gbc);
     80         set_gbc(2, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     81         add(resultLabel,gbc);
     82         set_gbc(2, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     83         add(resultField,gbc);
     84         set_gbc(3, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     85         add(calcButton,gbc);
     86         set_gbc(3, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     87         add(closeButton,gbc);
     88         set_gbc(4, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     89         add(resetButton,gbc);
     90         set_gbc(4, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
     91         add(startOvrButton,gbc);
     92         set_gbc(5,0,2,2, GridBagConstraints.HORIZONTAL, 10, 10);
     93         add(scrollPane2,gbc);
     94         set_gbc(7, 0, 2, 2, GridBagConstraints.BOTH, 10, 10);
     95                 gbc.weightx = 5.0;
     96                 gbc.weighty = 5.0;
     97         add(scrollPane,gbc);
     98         
     99         headingArea.append (addLine2 + newLine);
    100         
    101         outputArea.setEditable(false);  //text area for amortization table cannot be edited by user
    102         resultField.setEditable(false); //this indicates the result field can not be edited by the user
    103 
    104         mortgageTerms.addActionListener( //listener for combobox
    105                 new ActionListener() {
    106 
    107                     public void actionPerformed(ActionEvent evt) {
    108                         switch (mortgageTerms.getSelectedIndex()) {
    109                             case 0: monMorTerms = 84; intRate = 5.35 / 100 / 12;     break;
    110                             case 1: monMorTerms = 180; intRate = 5.5 / 100 / 12;    break;
    111                             case 2: monMorTerms = 360; intRate = 5.75 / 100 / 12; break;
    112                             default: monMorTerms = 84; intRate = 5.35 / 100 / 12; break; /*should allow user
    113                                                                                           *not to have to click
    114                                                                                           *first option, not working
    115                                                                                           *right though*/
    116                         }
    117                         }
    118                     });
    119         
    120                 
    121         
    122         
    123         closeButton.addActionListener(  //defines what the close button does
    124                 new ActionListener() {
    125 
    126                     public void actionPerformed(ActionEvent evt) {
    127                         if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Mortgage Calculator?",
    128                                 "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
    129                             System.exit(0);
    130                             }
    131                     }
    132         });
    133         
    134         calcButton.addActionListener( //defines what the calculate button does
    135                 new ActionListener() {
    136 
    137                     public void actionPerformed(ActionEvent evt) {
    138                         String firstNumText = firstNumField.getText();
    139                         double firstNum = Double.parseDouble(firstNumText);
    140                         double result = (firstNum * intRate) / (1 - Math.pow(1 + intRate, -monMorTerms));
    141                         NumberFormat nf = NumberFormat.getCurrencyInstance();
    142                         resultField.setText("" + nf.format(result));
    143                         
    144                         int paymentNum = 0; //initializes variables for while loop
    145                         double princLeft = firstNum;
    146                         double totalPaid = 0;
    147                         double intPaid = 0;
    148                         double princPaid = 0;
    149                         
    150                         
    151                         
    152                         
    153                         while (princLeft > 0) { //loop to calculate amortization table
    154                             ++paymentNum;
    155                             totalPaid = (totalPaid + result);
    156                             intPaid = (intRate * princLeft);
    157                             princPaid = (result - intPaid);
    158                             princLeft = (princLeft - princPaid);
    159                             String addLine = (paymentNum + "\t" + nf.format(result) + "\t" + nf.format(princLeft) + "\t" + nf.format(intPaid));
    160                             outputArea.append (addLine + newLine);
    161                         }
    162                         
    163                         
    164                         
    165                         
    166                         
    167                         
    168                     }
    169                 });
    170         
    171         resetButton.addActionListener(new ActionListener() { //defines what the reset button does
    172                 public void actionPerformed(ActionEvent e) {
    173                         firstNumField.setText("0");
    174                         resultField.setText("");
    175                         outputArea.setText("");
    176        
    177                 }
    178         });
    179         
    180         startOvrButton.addActionListener(  //defines what the close button does
    181                 new ActionListener() {
    182 
    183                     public void actionPerformed(ActionEvent evt) {
    184                         setVisible(false); //cleans up the calculator windowmakes the selection window visible
    185                         new MortgageCalculator().setVisible(true); //makes the selection window visible
    186                             
    187                     }
    188                 });
    189         
    190 
    191         
    192         setVisible(true); //ensures user can see window created
    193         }
    194                       
    195            
    196 }

    Line 48 currently sets the values of the array to use in my combo box. I just want to change it so that these strings are read from text file. I will still use the switch to set the values as I currently due in lines 104-118. Is there an easy to understand tutorial somewhere for this? The tutorial on the Oracle site just confuses me as well as other tutorials I have found.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reading from a sequential file to an array

    I need to pull these strings from a text file and enter them into an array
    For reading text the Scanner class is one easy way. It has methods to detect if there is more input that could be used to control a loop where you read each line and put it into an array.

  3. #3
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Reading from a sequential file to an array

    The API docs for java.io.BufferedReader have a code fragment in the description that should open up a file for you for line-at-a-time reading. readLine() in that class will get the lines, and JComboBox has a constructor that takes a Vector (which grows automagically as you add strings to it) argument.

  4. #4
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a sequential file to an array

    Thanks, know of any easy to understand tutorials for these ideas? I have looked at the Oracle tutorial site over and over and it just is not making sense to me.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reading from a sequential file to an array

    There are lots of sample programs here on the forum. Do a Search here for Scanner.

  6. #6
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a sequential file to an array

    Thanks for pointing me in the right direction everyone, I now have the program reading from a sequential file into an array. The only issue I am having is making the path anywhere except "/". I have tried several variations including c/Libraries/Documents and /Libraries/Documents. Any suggestions? The following is the code section I am referring to:

    Scanner scan = new Scanner(new File("/", "loanData.txt")); //provide file name from outside
            int counter = 0; //keep track of how many in the file
            while(scan.hasNextLine()) 
            {
                scan.nextLine();
                counter++;
            }
            Scanner scan2 = new Scanner(new File("/", "loanData.txt")); 
            String[] loanTerms = new String[counter];
            for(int i=0;i<counter;i++)
            {
                loanTerms[i]=scan2.nextLine(); //fill the array
            }

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reading from a sequential file to an array

    The only issue I am having is making the path
    When you look at paths on your OS, what is shown, say in Windows Explorer? That is what you need to use. Something like this:
    E:\\Backups

    You need two \s because the \ is a special character used to "escape" the following character.

  8. #8
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a sequential file to an array

    If needed, I have also included the code for all for classes and the text file in case anyone needs to run it.

    package week5;
     
    /**
     *
     * @author Chad McCoy
     */
     
    import java.io.FileNotFoundException; //these import everything needed for use in program
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*; 
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
     
     
    public class MortgageCalculator extends JFrame { //class definition
     
        //this section establishes variables
        JLabel lblTerms = new JLabel("Would you like to select from a list or enter loan terms manually?",JLabel.LEFT); 
     
        JRadioButton dropDown = new JRadioButton("List",true);
        JRadioButton manual = new JRadioButton("Manually",false);
        JRadioButton closeButton = new JRadioButton("Close");
     
        ButtonGroup radioGroup1 = new ButtonGroup();
     
        int i = 0;
     
        MortgageCalculator() {  //constructor for the class
            super("Term Option Settings"); //this makes a title for the window
            setLocation(500, 200); //this sets the location of the window
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); //the window will be disposed of, but program will still be running
            setLayout(new GridLayout(6, 1, 10, 10)); //defines window layout
            radioGroup1.add(dropDown); //buttons added to same group
            radioGroup1.add(manual);
            radioGroup1.add(closeButton);
     
            this.addWindowListener(new WindowAdapter() { /*this allows me to provide an option if the window is closed,
                                                           serves to ensure user wants to close the window*/
                public void windowClosed(WindowEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
     
                }
            }
            });
     
     
            add(lblTerms); //label and buttons added to GUI
            add(dropDown);
            add(manual);
            add(closeButton);
     
            dropDown.addActionListener( //defines action taken when the List button is selected
                    new ActionListener() {  
     
                        public void actionPerformed(ActionEvent evt) {
                            setVisible(false);
                    try {
                        MortgageCalc1 app = new MortgageCalc1();
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(MortgageCalculator.class.getName()).log(Level.SEVERE, null, ex);
                        setVisible(false); //cleans up the calculator windowmakes the selection window visible
                        new FnfError().setVisible(true);
                    }
                        }
                    });
     
            manual.addActionListener( //defines action taken when the Manual button is selected
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            setVisible(false);
                            MortgageCalc2 app = new MortgageCalc2();
                        }
                    });
     
            closeButton.addActionListener(  //defines what the close button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
                                }
                        }
            });
     
     
            pack(); //packs the contents to the frame making the Window just the right size for contents
            setVisible(true);  //ensures user can see window created
     
        }
     
        public static void main(String[] args) throws Exception { 
     
     
     
     
     
            MortgageCalculator app = new MortgageCalculator(); //creates a new instance of the MortgageCalculator class
     
        }
    }
    package week5;
     
    /**
     *
     * @author Chad McCoy
     */
     
    import java.awt.*; //these import everything needed for use in program
    import java.io.FileNotFoundException;
    import java.text.NumberFormat;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.File;
    import javax.swing.*;
    import java.util.Scanner;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane; 
     
     
    public class MortgageCalc1 extends JFrame {  //class definition
        GridBagConstraints gbc = new GridBagConstraints();
        private void set_gbc(int row, int column, int width, int height, int fill, int v, int h) {
                       gbc.gridy = row;
                       gbc.gridx = column;
                       gbc.gridwidth = width;
                       gbc.gridheight = height;
                       gbc.fill = fill;
                       gbc.ipady = v;
                       gbc.ipadx = h;
     
                    }
     
        JLabel firstNumLabel = new JLabel("Mortgage Principal:"); //this section establishes variables
        JTextField firstNumField = new JTextField("0");
     
        JLabel resultLabel = new JLabel("Payment Amount:");
        JTextField resultField = new JTextField("0");
     
        JLabel comboOptions = new JLabel("Term Options");
     
        JButton calcButton = new JButton("Calculate Payment");
        JButton closeButton = new JButton("Close");
        JButton resetButton = new JButton("Reset Calculator");
        JButton startOvrButton = new JButton("Start Over");
     
        public int pymtAmt = 0;
        public double intRate = 0;
        public int monMorTerms = 0;
     
        String[] loanTerms;
        JComboBox mortgageTerms;
     
        int i;
     
        JTextArea outputArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(outputArea);
     
        JTextArea headingArea = new JTextArea();
        JScrollPane scrollPane2 = new JScrollPane(headingArea);
     
        private final static String newLine = "\n";
     
        String addLine2 = ("Pmt#" + "\t" + "Pmt Amt" + "\t" + "Loan Bal" + "\t" + "Int Paid");
     
     
     
        public MortgageCalc1() throws FileNotFoundException  {  //constructor for the class
            super("Mortgage Calculator"); //this makes a title for the window
            setLocation(500, 200); //this sets the location of the window
            setSize (360,500); //sets the window size
            setResizable(true); //allows user to resize window
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); //the window will be disposed of, but program will still be running
            setLayout(new GridBagLayout()); //defines window layout
     
            this.addWindowListener(new WindowAdapter() { /*this allows me to provide an option if the window is closed,
                                                           serves to ensure user wants to close the window*/
                public void windowClosed(WindowEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
                }
            }
            });
     
            Scanner scan = new Scanner(new File("/", "loanData.txt")); //provide file name from outside
            int counter = 0; //keep track of how many in the file
            while(scan.hasNextLine()) 
            {
                scan.nextLine();
                counter++;
            }
            Scanner scan2 = new Scanner(new File("/", "loanData.txt")); 
            String[] loanTerms = new String[counter];
            for(int i=0;i<counter;i++)
            {
                loanTerms[i]=scan2.nextLine(); //fill the array
            }
     
            final JComboBox mortgageTerms = new JComboBox(loanTerms);
     
     
     
            set_gbc(0, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10); //establishes contraints for gridbag
            add(firstNumLabel,gbc); //these lines add the elements to the window
            set_gbc(0, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(firstNumField,gbc);
            set_gbc(1, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(comboOptions,gbc);
            set_gbc(1, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(mortgageTerms,gbc);
            set_gbc(2, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(resultLabel,gbc);
            set_gbc(2, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(resultField,gbc);
            set_gbc(3, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(calcButton,gbc);
            set_gbc(3, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(closeButton,gbc);
            set_gbc(4, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(resetButton,gbc);
            set_gbc(4, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(startOvrButton,gbc);
            set_gbc(5,0,2,2, GridBagConstraints.HORIZONTAL, 10, 10);
            add(scrollPane2,gbc);
            set_gbc(7, 0, 2, 2, GridBagConstraints.BOTH, 10, 10);
                    gbc.weightx = 5.0;
                    gbc.weighty = 5.0;
            add(scrollPane,gbc);
     
            headingArea.append (addLine2 + newLine);
     
            outputArea.setEditable(false);  //text area for amortization table cannot be edited by user
            resultField.setEditable(false); //this indicates the result field can not be edited by the user
     
            mortgageTerms.addActionListener( //listener for combobox
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            switch (mortgageTerms.getSelectedIndex()) {
                                case 1: monMorTerms = 84; intRate = 5.35 / 100 / 12;     break;
                                case 2: monMorTerms = 120; intRate = 5.0 / 100 / 12;    break;
                                case 3: monMorTerms = 240; intRate = 5.65 / 100 / 12; break;
                                case 4: monMorTerms = 360; intRate = 5.75 / 100 / 12; break; 
                            }
                            }
                        });
     
     
     
     
            closeButton.addActionListener(  //defines what the close button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
                                }
                        }
            });
     
            calcButton.addActionListener( //defines what the calculate button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            String firstNumText = firstNumField.getText();
                            double firstNum = Double.parseDouble(firstNumText);
                            double result = (firstNum * intRate) / (1 - Math.pow(1 + intRate, -monMorTerms));
                            NumberFormat nf = NumberFormat.getCurrencyInstance();
                            resultField.setText("" + nf.format(result));
     
                            int paymentNum = 0; //initializes variables for while loop
                            double princLeft = firstNum;
                            double totalPaid = 0;
                            double intPaid = 0;
                            double princPaid = 0;
     
     
     
     
                            while (princLeft > 0) { //loop to calculate amortization table
                                ++paymentNum;
                                totalPaid = (totalPaid + result);
                                intPaid = (intRate * princLeft);
                                princPaid = (result - intPaid);
                                princLeft = (princLeft - princPaid);
                                String addLine = (paymentNum + "\t" + nf.format(result) + "\t" + nf.format(princLeft) + "\t" + nf.format(intPaid));
                                outputArea.append (addLine + newLine);
                            }
     
     
     
     
     
     
                        }
                    });
     
            resetButton.addActionListener(new ActionListener() { //defines what the reset button does
                    public void actionPerformed(ActionEvent e) {
                            firstNumField.setText("0");
                            resultField.setText("");
                            outputArea.setText("");
     
                    }
            });
     
            startOvrButton.addActionListener(  //defines what the start over button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            setVisible(false); //cleans up the calculator windowmakes the selection window visible
                            new MortgageCalculator().setVisible(true); //makes the selection window visible
     
                        }
                    });
     
     
     
            setVisible(true); //ensures user can see window created
            }
     
     
    }
     
    package week5;
     
    /*
     *
     * @author Chad McCoy
     */
     
    import java.awt.*; //these import everything needed for use in program
    import java.text.NumberFormat;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
     
    public class MortgageCalc2 extends JFrame {  //class definition
        GridBagConstraints gbc = new GridBagConstraints();
        private void set_gbc(int row, int column, int width, int height, int fill, int v, int h) {
                       gbc.gridy = row;
                       gbc.gridx = column;
                       gbc.gridwidth = width;
                       gbc.gridheight = height;
                       gbc.fill = fill;
                       gbc.ipady = v;
                       gbc.ipadx = h;
     
                    }
     
        JLabel firstNumLabel = new JLabel("Mortgage Principal:"); //this section establishes variables
        JTextField firstNumField = new JTextField("0");
     
        JLabel secondNumLabel = new JLabel("Mortgage Terms (in years):");
        JTextField secondNumField = new JTextField("0");
     
        JLabel thirdNumLabel = new JLabel("Annual Percentage Rate (APR)");
        JTextField thirdNumField = new JTextField("0");
     
        JLabel resultLabel = new JLabel("Payment Amount:");
        JTextField resultField = new JTextField("0");
     
        JButton calcButton = new JButton("Calculate Payment");
        JButton closeButton = new JButton("Close");
        JButton resetButton = new JButton("Reset Calculator");
        JButton startOvrButton = new JButton("Start Over");
     
        public int pymtAmt = 0;
        public double intRate = 0;
        public int monMorTerms = 0;
     
        JTextArea outputArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(outputArea);
     
        JTextArea headingArea = new JTextArea();
        JScrollPane scrollPane2 = new JScrollPane(headingArea);
     
        private final static String newLine = "\n";
     
        String addLine2 = ("Pmt#" + "\t" + "Pmt Amt" + "\t" + "Loan Bal" + "\t" + "Int Paid");
     
        public MortgageCalc2() {  //constructor for object of this class
            super("Mortgage Calculator"); //this makes a title for the window
            setLocation(500, 200); //this sets the location of the window
            setSize (360,500); //sets the window size
            setResizable(true); //allows user to resize window
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); //the window will be disposed of, but program will still be running
            setLayout(new GridBagLayout()); //defines window layout
     
            this.addWindowListener(new WindowAdapter() { /*this allows me to provide an option if the window is closed,
                                                           serves to ensure user wants to close the window*/
                public void windowClosed(WindowEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
                }
            }
            });
     
            set_gbc(0, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10); //establishes contraints for gridbag
            add(firstNumLabel,gbc); //these lines add the elements to the window
            set_gbc(0, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(firstNumField,gbc);
            set_gbc(1, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(secondNumLabel,gbc);
            set_gbc(1, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(secondNumField,gbc);
            set_gbc(2, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(thirdNumLabel,gbc);
            set_gbc(2, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(thirdNumField,gbc);
            set_gbc(3, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(resultLabel,gbc);
            set_gbc(3, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(resultField,gbc);
            set_gbc(4, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(calcButton,gbc);
            set_gbc(4, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(closeButton,gbc);
            set_gbc(5, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(resetButton,gbc);
            set_gbc(5, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(startOvrButton,gbc);
            set_gbc(6,0,2,2, GridBagConstraints.HORIZONTAL, 10, 10);
            add(scrollPane2,gbc);
            set_gbc(8, 0, 2, 2, GridBagConstraints.BOTH, 10, 10);
                    gbc.weightx = 5.0;
                    gbc.weighty = 5.0;
            add(scrollPane,gbc);
     
            headingArea.append (addLine2 + newLine);
     
            outputArea.setEditable(false);  //text area for amortization table cannot be edited by user
            resultField.setEditable(false); //this indicates the result field can not be edited by the user
     
            closeButton.addActionListener(  //defines what the close button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) { 
                            if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
                                }
                        }
            });
     
            calcButton.addActionListener( //defines what the calculate button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            String firstNumText = firstNumField.getText();
                            String secondNumText = secondNumField.getText();
                            String thirdNumText = thirdNumField.getText();
                            double firstNum = Double.parseDouble(firstNumText);
                            double secondNum = Double.parseDouble(secondNumText);
                            double thirdNum = Double.parseDouble(thirdNumText);
                            double intRate = thirdNum / 100 / 12;
                            double monMorTerms = secondNum * 12;
                            double result = (firstNum * intRate) / (1 - Math.pow(1 + intRate, -monMorTerms));
                            NumberFormat nf = NumberFormat.getCurrencyInstance();
                            resultField.setText("" + nf.format(result));
     
                            int paymentNum = 0; //initializes variables for while loop
                            double princLeft = firstNum;
                            double totalPaid = 0;
                            double intPaid = 0;
                            double princPaid = 0;
     
     
     
     
                            while (princLeft > 0) { //loop to calculate amortization table
                                ++paymentNum;
                                totalPaid = (totalPaid + result);
                                intPaid = (intRate * princLeft);
                                princPaid = (result - intPaid);
                                princLeft = (princLeft - princPaid);
                                String addLine = (paymentNum + "\t" + nf.format(result) + "\t" + nf.format(princLeft) + "\t" + nf.format(intPaid));
                                outputArea.append (addLine + newLine);
                            }
     
                        }
                    });
     
            resetButton.addActionListener(new ActionListener() { //defines what the reset button does
                    public void actionPerformed(ActionEvent e) {
                            firstNumField.setText("0");
                            secondNumField.setText("0");
                            thirdNumField.setText("0");
                            resultField.setText("");
                            outputArea.setText("");
                    }
                    });
     
            startOvrButton.addActionListener(  //defines what the close button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            setVisible(false); //cleans up the calculator windowmakes the selection window visible
                            new MortgageCalculator().setVisible(true); //makes the selection window visible
                        }
                    });
     
            setVisible(true); //ensures user can see window created
        }
     
    }
     
    package week5;
     
    import javax.swing.*; //these import everything needed for use in program
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
     
    /**
     *
     * @author Chad McCoy
     */
    public class FnfError extends JFrame { //class definition
     
        GridBagConstraints gbc = new GridBagConstraints();
        private void set_gbc(int row, int column, int width, int height, int fill, int v, int h) {
                       gbc.gridy = row;
                       gbc.gridx = column;
                       gbc.gridwidth = width;
                       gbc.gridheight = height;
                       gbc.fill = fill;
                       gbc.ipady = v;
                       gbc.ipadx = h;
     
                    }
     
        JLabel errorMsgLabel = new JLabel("The file was not found, "); //this section establishes variables
        JLabel errorMsg2Label = new JLabel("please select manually");
     
        JButton manualButton = new JButton("Manually");
        JButton closeButton = new JButton("Close");
     
        public FnfError () { //constructor for object of this class
            super("Mortgage Calculator"); //this makes a title for the window
            setLocation(500, 200); //this sets the location of the window
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); //the window will be disposed of, but program will still be running
     
     
            setLayout(new GridBagLayout()); //defines window layout
     
            this.addWindowListener(new WindowAdapter() { /*this allows me to provide an option if the window is closed,
                                                           serves to ensure user wants to close the window*/
                public void windowClosed(WindowEvent e) {
                    if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
                }
            }
            });
     
            set_gbc(0, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10); //establishes contraints for gridbag
            add(errorMsgLabel,gbc); //these lines add the elements to the window
            set_gbc(0, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(errorMsg2Label,gbc);
            set_gbc(1, 0, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(closeButton,gbc);
            set_gbc(1, 1, 1, 1, GridBagConstraints.HORIZONTAL, 10, 10);
            add(manualButton,gbc);
     
     
            manualButton.addActionListener(  //defines what the close button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            setVisible(false); //cleans up the calculator windowmakes the selection window visible
                            new MortgageCalc2().setVisible(true); //makes the selection window visible
                        }
                    });
     
            closeButton.addActionListener(  //defines what the close button does
                    new ActionListener() {
     
                        public void actionPerformed(ActionEvent evt) {
                            if (JOptionPane.showConfirmDialog(null, "Are you sure you wish to close the Week 5 Mortgage Calculator?",
                                    "Quit", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                System.exit(0);
                                }
                        }
            });
            pack(); //packs the contents to the frame making the Window just the right size for contents
            setVisible(true); //ensures user can see window created
     
     
        }
    }

    and the text file is

    Select Terms
    7 years at 5.35%
    10 years at 5%
    20 years at 5.65%
    30 years at 5.75

  9. #9
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a sequential file to an array

    I replaced the "/" with "C://Users/Xrrak" and that did the trick. Thanks again.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reading from a sequential file to an array

    "C://Users/Xrrak"
    try removing the extra /
    "C:/Users/Xrrak"

  11. #11
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a sequential file to an array

    That worked as well. Thinking on it though I guess it is simplest to have it look on the main drive, unless there is a way to tell the program that the text file is in the same place the program is run from, where ever that may be...

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reading from a sequential file to an array

    the same place the program is run from
    Use the File constructor with only the filename

  13. #13
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a sequential file to an array

    Scanner scan = new Scanner(new File("loanData.txt")); //provide file name from outside
    int counter = 0; //keep track of how many in the file
    while(scan.hasNextLine())
    {
    scan.nextLine();
    counter++;
    }
    Scanner scan2 = new Scanner(new File("loanData.txt"));
    String[] loanTerms = new String[counter];
    for(int i=0;i<counter;i++)
    {
    loanTerms[i]=scan2.nextLine(); //fill the array
    }

    I changed to this but I get a FileNotFound error

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reading from a sequential file to an array

    in the same place the program is run from
    How are you running the program? IDE's mess up what you might think about where files are.
    Create a File object with the filename you want to use and then print out the File object's absolute path to see where the JVM thinks it should look for the file.

  15. #15
    Junior Member
    Join Date
    Apr 2010
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading from a sequential file to an array

    I am using netbeans and I put the file in the src folder for the project with the java files.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Reading from a sequential file to an array

    I have no idea where the current directory is for a program executing in an IDE.
    Did you try this:
    Create a File object with the filename you want to use and then print out the File object's absolute path to see where the JVM thinks it should look for the file.

Similar Threads

  1. Sequential Files!!!???
    By nitwit3 in forum Java Theory & Questions
    Replies: 7
    Last Post: July 27th, 2011, 08:22 AM
  2. Reading lines of a text file into a string array
    By fortune2k in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 11th, 2010, 11:56 AM
  3. Reading a file, then putting it in an array
    By Gondee in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 16th, 2010, 11:11 AM
  4. Anyone Help me in XML file Reading??????????
    By goplrao in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: May 2nd, 2010, 11:04 AM
  5. Reading .txt and storing into an array
    By vluong in forum Collections and Generics
    Replies: 1
    Last Post: January 4th, 2010, 02:07 PM