I'm receiving the following errors when trying to read from a file:

java.io.FileNotFoundException: rates.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at MortgageCalculator4.submitButtonActionPerformed(MortgageCalculator4.java:187)
at MortgageCalculator4.access$000(MortgageCalculator4.java:20)
at MortgageCalculator4$1.actionPerformed(MortgageCalculator4.java:70)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6288)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6053)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4651)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:616)
at java.awt.EventQueue$2.run(EventQueue.java:614)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)


I am using NetBeans and have the rates.txt file in the correct directory, but can't seem to figure out how to get the program to read from the file. I've looked at numerous examples on the Internet and have tried several different approaches with no luck. Any pointers would be greatly appreciated. Here's the code.

import java.awt.*; // All awt classes available. Classes used to build GUI's
import java.awt.event.*; // Awt event package used for handling events
import javax.swing.*; // All swing classes available. Classes used to build GUI's
import javax.swing.event.*; // Swing event package used for handling events
import java.util.*; // Get locale object to get US currency and scanner object
import java.text.*; // Import classes for formatting
import java.io.*;

public class MortgageCalculator4 extends javax.swing.JFrame { // Class MortgageCalculator4 calculates and displays mortgage payment data with a GUI 
    
    // Creates new form MortgageCalculator4
    public MortgageCalculator4() {
        initComponents();
    }
    
    // This method is called from within the constructor to initialize the form
    // The NetBeans GUI Builder provides a set of user interface components from which GUI forms can be built
    // The IDE's GUI Builder assists in designing and building Java forms by providing a series of tools that simplify the process                          
    private void initComponents() {
        
        // Create components
        mortgageAmount = new javax.swing.JTextField();
        mortgagePaymentAmount = new javax.swing.JTextField(); 
        mortgageAmountLabel = new javax.swing.JLabel();
        mortgagePaymentAmountLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        amortizationSchedule = new javax.swing.JTextArea();
        amortizationScheduleLabel = new javax.swing.JLabel();
        submitButton = new javax.swing.JButton();
        resetButton = new javax.swing.JButton();
        quitButton = new javax.swing.JButton();
        availableMortgageLoansLabel = new javax.swing.JLabel();
        sevenYearLoan = new javax.swing.JRadioButton();
        fifteenYearLoan = new javax.swing.JRadioButton();
        thirtyYearLoan = new javax.swing.JRadioButton();
        
        // Use button group so turning on one button turns off all others in the group
        ButtonGroup loans = new ButtonGroup();
        loans.add(sevenYearLoan);
	loans.add(fifteenYearLoan);
	loans.add(thirtyYearLoan);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); // Closes window (X)
        
        setTitle("McBride Financial Services Mortgage Calculator");  // Strings for title and labels
        mortgageAmountLabel.setText("Enter the amount of the mortgage (no punctuation)");
        availableMortgageLoansLabel.setText("Select from the available mortgage loans");
        mortgagePaymentAmountLabel.setText("Mortgage payment amount");
        amortizationScheduleLabel.setText("Amortization schedule (Payment number, Loan balance, and Interest paid ");
        
        amortizationSchedule.setColumns(5);  // Set JTextArea and edit abilities
        amortizationSchedule.setEditable(false);
        amortizationSchedule.setRows(20);
        jScrollPane1.setViewportView(amortizationSchedule);
        
        submitButton.setText("Submit"); // String for button
        submitButton.addActionListener(new java.awt.event.ActionListener() { // Connection wizard - assists in setting events between components in a form without the need of writing code manually
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitButtonActionPerformed(evt);
            }
        });
       
        resetButton.setText("Reset"); // String for button
        resetButton.addActionListener(new java.awt.event.ActionListener() { // Connection wizard - assists in setting events between components in a form without the need of writing code manually
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });

        quitButton.setText("Quit"); // String for button
        quitButton.addActionListener(new java.awt.event.ActionListener() { // Connection wizard - assists in setting events between components in a form without the need of writing code manually
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitButtonActionPerformed(evt);
            }
        });

        sevenYearLoan.setText("7 years at 5.35%"); // String for button
        sevenYearLoan.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); // Set button's border and margin
        sevenYearLoan.setMargin(new java.awt.Insets(0, 0, 0, 0));

        fifteenYearLoan.setText("15 years at 5.5%"); // String for button
        fifteenYearLoan.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); // Set button's border and margin
        fifteenYearLoan.setMargin(new java.awt.Insets(0, 0, 0, 0));

        thirtyYearLoan.setText("30 years at 5.75%"); // String for button
        thirtyYearLoan.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); // Set button's border and margin
        thirtyYearLoan.setMargin(new java.awt.Insets(0, 0, 0, 0));
        
        // Set text field's edit abilities
        mortgagePaymentAmount.setEditable(false);
        
        // Generated code from IDE's GUI Builder to add, group, and set the lay out of the components
        // The GUI Builder enables you to lay out forms by utilizing drag and drop techniques with the components
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(mortgagePaymentAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(mortgagePaymentAmountLabel))
                    .addComponent(sevenYearLoan)
                    .addComponent(thirtyYearLoan)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(mortgageAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(mortgageAmountLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(fifteenYearLoan)
                        .addGap(17, 17, 17)
                        .addComponent(availableMortgageLoansLabel))
                    .addComponent(amortizationScheduleLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(submitButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(resetButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(quitButton)))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {mortgageAmount, mortgagePaymentAmount});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(mortgageAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(mortgageAmountLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sevenYearLoan)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fifteenYearLoan)
                    .addComponent(availableMortgageLoansLabel))
                .addGap(5, 5, 5)
                .addComponent(thirtyYearLoan)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(mortgagePaymentAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(mortgagePaymentAmountLabel))
                .addGap(21, 21, 21)
                .addComponent(amortizationScheduleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(submitButton)
                    .addComponent(resetButton)
                    .addComponent(quitButton))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>
    
    private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) { // ActionListener added to button
        String line = null;
        
        // define array to hold values of the three different loans
        double[][] mortgages =    // element 0 = term in years; element 1 = interest rate
        {{7, 0.0, 0.0, 0.0, 0.0},  // element 2 = mortgage payment amount; element 3 = interest payement
         {15, 0.0, 0.0, 0.0, 0.0}, // element 4 = principal payment
         {30, 0.0, 0.0, 0.0, 0.0}};
        
        String amountEntered;
        double mortgAmt = 0;
        int payment = 0;

        try {
            File ratesFile = new File("rates.txt");
            Scanner in = new Scanner(ratesFile);
            int i = 0;
            while (in.hasNextDouble()) {
                mortgages[i][1] = in.nextDouble();
                i++;  
                in.close();
            }
        }
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
       
        // Dialog to inform user of invalid input
        Component frame = null;
        
        if (evt.getSource()==submitButton) { 

            amortizationSchedule.setText(""); // clear text area on submit
            
        }
                
        try {
                  
            // Get user input
            amountEntered = mortgageAmount.getText();
            // Parse input
            mortgAmt = Double.parseDouble(amountEntered);
            
            if (mortgAmt<=0) throw new NumberFormatException(); 
            
         }
                
        catch(NumberFormatException n) {
               
        }    
        
        if (mortgAmt<=0) {
            
            JOptionPane.showMessageDialog(frame, "Please enter number values that are > 0.");
            mortgageAmount.setText("");
            mortgagePaymentAmount.setText("");
            return;
            
        }

        // loop through array to get proper values and mortgage payment amounts
        for (int i=0; i<=2; i++) {
        
            // convert loan terms to months 
            mortgages[i][0] = mortgages[i][0]*12;
        
            // calculate monthly interest rates 
            mortgages[i][1] = mortgages[i][1]/100/12;
        
            // calculate mortgage payment amounts
            mortgages[i][2] = mortgAmt*mortgages[i][1]/(1-(Math.pow((1+mortgages[i][1]), 
                (-mortgages[i][0]))));
            
        }
            
            while (sevenYearLoan.isSelected() && payment<mortgages[0][0]) { // Loop through loan for amortization schedule
            
                payment++;
                // Write the mortgage payment amount in the correct format to the mortgagePaymentAmount JTextField
                NumberFormat nfmonthlyPayment = NumberFormat.getCurrencyInstance(Locale.US);
                mortgagePaymentAmount.setText(" " + nfmonthlyPayment.format(mortgages[0][2]));
                
                // amortization formulas
                mortgages[0][3] = mortgAmt*mortgages[0][1];
                mortgages[0][4] = mortgages[0][2]-mortgages[0][3];
                mortgAmt = mortgAmt-mortgages[0][4];
                
                // Display amortization schedule in the JTextArea
                amortizationSchedule.setText(amortizationSchedule.getText() +
                    payment + ".  " + nfmonthlyPayment.format(mortgAmt) + "    " 
                    + nfmonthlyPayment.format(mortgages[0][3]) +"\n");
            
            }
            
            while (fifteenYearLoan.isSelected() && payment<mortgages[1][0]) { // Loop through loan for amortization schedule
            
                payment++;
                // Write the mortgage payment amount in the correct format to the mortgagePaymentAmount JTextField
                NumberFormat nfmonthlyPayment = NumberFormat.getCurrencyInstance(Locale.US);
                mortgagePaymentAmount.setText(" " + nfmonthlyPayment.format(mortgages[1][2]));
                
                // amortization formulas
                mortgages[1][3] = mortgAmt*mortgages[1][1];
                mortgages[1][4] = mortgages[1][2]-mortgages[1][3];
                mortgAmt = mortgAmt-mortgages[1][4];
                
                // Display amortization schedule in the JTextArea
                amortizationSchedule.setText(amortizationSchedule.getText() + 
                    payment + ".  " + nfmonthlyPayment.format(mortgAmt) + "    " 
                    + nfmonthlyPayment.format(mortgages[1][3]) +"\n");
            
            }
            
            while (thirtyYearLoan.isSelected() && payment<mortgages[2][0]) { // Loop through loan for amortization schedule
            
                payment++;
                // Write the mortgage payment amount in the correct format to the mortgagePaymentAmount JTextField
                NumberFormat nfmonthlyPayment = NumberFormat.getCurrencyInstance(Locale.US);
                mortgagePaymentAmount.setText(" " + nfmonthlyPayment.format(mortgages[2][2]));
                
                // amortization formulas
                mortgages[2][3] = mortgAmt*mortgages[2][1];
                mortgages[2][4] = mortgages[2][2]-mortgages[2][3];
                mortgAmt = mortgAmt-mortgages[2][4];
                
                // Display amortization schedule in the JTextArea
                amortizationSchedule.setText(amortizationSchedule.getText() + 
                    payment + ".  " + nfmonthlyPayment.format(mortgAmt) + "    " 
                    + nfmonthlyPayment.format(mortgages[2][3]) +"\n");
            
            }
        
    }
        
    private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {   
        
            // ActionListener added to button
            // Quits program when button pushed
            System.exit(1);
    }                                          

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
            
            // ActionListener added to button
            // Resets fields when button pushed
            mortgageAmount.setText("");
            mortgagePaymentAmount.setText("");
            amortizationSchedule.setText("");
    }                                           
    
    public static void main(String args[]) { // Main method schedules job for the event dispatch thread and creates and shows the GUI
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MortgageCalculator4().setVisible(true);
            }
        });
    }
    
    // Variables declaration   
    private javax.swing.JTextField mortgageAmount;
    private javax.swing.JTextArea amortizationSchedule;
    private javax.swing.JLabel amortizationScheduleLabel;
    private javax.swing.JLabel availableMortgageLoansLabel;
    private javax.swing.JRadioButton fifteenYearLoan;
    private javax.swing.JScrollPane jScrollPane1; 
    private javax.swing.JLabel mortgageAmountLabel;
    private javax.swing.JTextField mortgagePaymentAmount;
    private javax.swing.JLabel mortgagePaymentAmountLabel;
    private javax.swing.JButton submitButton;
    private javax.swing.JButton quitButton;
    private javax.swing.JButton resetButton;
    private javax.swing.JRadioButton sevenYearLoan;
    private javax.swing.JRadioButton thirtyYearLoan;               
    
}

have the rates.txt file in the correct directory

Are you sure?
Your IDE is fussy about where it wants files put.
What happens if you take the program outside the IDE and execute it?

For resolving this problem, get rid of 95% of this code and work with a simple program that uses the Scanner etc to try to read the file. Try putting files with the same name but different contents in all the possible places the IDE could look. Your program should read one of them. The contents of the file read should show you which file was read.

Thanks for the reply. I have saved the text file in the same directory as all of my .java files. Unfortunately, I haven't been able to run any programs outside of an IDE due to my system settings and such. I'll try and create a small program to see if I have any luck in reading text files. I did try and use the path name, but received an error along the lines of:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Scanner closed

Scanner closed

The message says what the problem was.

Okay, duh...I see. Thanks for the help. I really appreciate it. I got it working now with the path approach.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.