Java Error

Hello, I am receiving an error with a homework assignment.  The program is supposed to call interest rates and loan term information from an external file.  I have included a package called Week 5 that is also part of the assignment.  The program runs without error without the package, but when I include it I receive this.  Here is also the code .  Thank you
ERROR:
C:\Prg421\Week5>javac Mort6.java

C:\Prg421\Week5>cd..

C:\Prg421>java Week5.Mort6
java.io.FileNotFoundException: data.txt (The system cannot find the file specifi
ed)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.io.FileReader.<init>(Unknown Source)
        at Week5.Mort6.load(Mort6.java:87)
        at Week5.Mort6.<init>(Mort6.java:73)
        at Week5.Mort6$1.run(Mort6.java:428)
        at java.awt.event.InvocationEvent.dispatch(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)

C:\Prg421>

My external file is located in my Week 5 directory along with the calsses for my program and is structured like this
7,5.35
15,5.50
30,5.75
Any one have any ideas????
/*
 PRG 421 Java Programming II  Change Request 7, Week 5
 Date: May 9, 2009
 Filename: Mort6.java
 Purpose: Write the program in Java (with a graphical user interface) and have it calculate and display the mortgage payment amount from 
 
user input of the amount of the mortgage and the user's selection from a menu of available mortgage loans. Use an array for the mortgage 
 
data for the different loans. Read the interest rates to fill the array from a sequential file. Display the mortgage payment amount 
 
followed by the loan balance and interest paid for each payment over the term of the loan. Add graphics in the form of a chart. Allow 
 
the user to loop back and enter a new amount and make a new selection or quit. Please insert comments in the program to document the 
 
program.
 */
 
package Week5;
 
import java.awt.*;
import java.awt.event.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.font.*;
import java.awt.Font;
import java.awt.geom.*;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.io.FileReader;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
 
 
public class Mort6 extends JFrame implements ActionListener
{
     JLabel Llabel;
     JTextField Ltextfield;
     JLabel Olabel;
     JComboBox options;
     JLabel Tlabel;
     JTextField Ttextfield;
     JLabel Rlabel;
     JTextField Rtextfield;
     JLabel Plabel;
     JLabel $label;
     JButton calculate;
     JButton reset;
     JButton end;
     JTable table;
     JMenuItem mnuExit = new JMenuItem("Exit");
     DefaultTableModel model;
     double[] trmArray;
     double[] intrstArray;
     JButton graph;
     private float[]  yearlyPrinciple;
     private float[]  yearlyInterest;
 
     // Title
     public Mort6 ()
     {
          super("Nate Himley Week 5");
          setDefaultLookAndFeelDecorated(true);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          load();
          init();
          pack();
          setVisible(true);
     }
 
     //Pull info from file
 
     public void load()
     {
          Reader fis;
               try
               {
 
                    fis = new FileReader("data.txt");
 
                    BufferedReader b = new BufferedReader( fis );
                    String inputholder = "";
                    String termsandrates = "";
                    while ((inputholder = b.readLine()) != null)
                    {
                    termsandrates = termsandrates + inputholder + ",";
                    }
                    String[] line = termsandrates.split(",");
                    trmArray = new double[3];
                    trmArray[0] = Double.parseDouble(line[0].trim());
                    trmArray[1] = Double.parseDouble(line[2].trim());
                    trmArray[2] = Double.parseDouble(line[4].trim());
                                   
                    intrstArray = new double[3];
                    intrstArray[0] = Double.parseDouble(line[1].trim());
                    intrstArray[1] = Double.parseDouble(line[3].trim());
                    intrstArray[2] = Double.parseDouble(line[5].trim());
 
               b.close();
               fis.close();
               }
 
               catch ( Exception e1 )
               {
                    e1.printStackTrace(  );
               }
     }
 
     //labels, buttons and textfields
 
     public void init()
     {
          Mort6Layout customLayout = new Mort6Layout();
 
          Container con = getContentPane();
          con.setLayout(customLayout);
 
          con.setFont(new Font("Arial", Font.PLAIN, 12));
          con.setLayout(customLayout);
 
          Llabel = new JLabel("Mortgage Loan Amount $ (no comma)");
          con.add(Llabel);
 
          Ltextfield = new JTextField("");
          con.add(Ltextfield);
 
          Olabel = new JLabel("Term & Interest Rate %");
          con.add(Olabel);
 
          options = new JComboBox();
          con.add(options);
 
          options.addItem(" (Preset rate)");
          options.addItem("7 years at 5.35%");
          options.addItem("15 years at 5.5%");
          options.addItem("30 years at 5.75%");
 
          Tlabel = new JLabel("Term (years)");
          con.add(Tlabel);
 
          Ttextfield = new JTextField("");
          con.add(Ttextfield);
 
          Rlabel = new JLabel("Interest Rate");
          con.add(Rlabel);
 
          Rtextfield = new JTextField("");
          con.add(Rtextfield);
 
          Plabel = new JLabel("Monthly Payment Amount");
          con.add(Plabel);
 
          $label = new JLabel("");
          con.add($label);
 
          calculate = new JButton("Calculate");
          con.add(calculate);
          calculate.setBackground(Color.white);
 
          reset = new JButton("Clear");
          con.add(reset);
          reset.setBackground(Color.white);
 
          end = new JButton ("End");
          con.add(end);
          end.setBackground(Color.white);
 
                    //table header names
          String[] columnNames = {"Payment #","Payment Amount", "Interest", "Principle Reduction",
                                             "Remaining Balance"};
 
          //create table and table model
          model = new DefaultTableModel(columnNames, 0);
          table = new JTable(model);
          JScrollPane scroll = new JScrollPane(table);
          table.setPreferredScrollableViewportSize(new Dimension (10, 600));
          con.add (scroll);
 
          graph = new JButton ("See Graph");
          con.add(graph);
          graph.setBackground(Color.white);
 
          //action listeners
          Ltextfield.addActionListener(this);
          options.addActionListener(this);
          calculate.addActionListener(this);
          reset.addActionListener(this);
          end.addActionListener(this);
          graph.addActionListener(this);
     }
 
 
     //action event from listeners
     public void actionPerformed(ActionEvent event)
     {
     Object source = event.getSource();
          if (source == calculate)
          {
               startCalculations();
          }
 
          if (source == reset)
          {
               reset();
          }
 
          if (source==options)
          {
               setRate();
          }
 
          if (source == end)
          {
               exit();
          }
 
          if (source == mnuExit)
          {
            exitGraph();
           }
          if (source == graph)
          {
               mFrame = new JFrame("Mortgage Graph");
               mFrame.getContentPane().add(new GraphPanel(yearlyPrinciple, yearlyInterest));
               mFrame.setSize(800,600);
               mFrame.setLocation(200,100);
 
             //trying to create menu
             // Create an instance of the menu (Creates the Menu Bar)
                 JMenuBar mnuBar = new JMenuBar();
                 mFrame.setJMenuBar(mnuBar);
 
             // Construct and populate the Exit menu (Creates the Exit Menu)
                 JMenu mnuExitbar = new JMenu ("End", true);
                 mnuBar.add(mnuExitbar);
                 mnuExitbar.add(mnuExit);
 
        mFrame.setVisible(true);
 
               //exit listener
                mnuExit.addActionListener(this);
          }
        }
          public JFrame mFrame = new JFrame();
 
 
void exitGraph()
{
 
             mFrame.dispose();
             mFrame = null;
          }
 
          void setRate()
     {
          int index = options.getSelectedIndex();
 
          //term and interest error check
          if (index > 0)
          {
               try
               {
                    Ttextfield.setText(Double.toString(trmArray[index-1]));
               }
 
               catch (NumberFormatException e)
               {
                    JOptionPane.showMessageDialog(null, "Invalid or missing Loan Term.  Please try again!",
                                                            "Error", JOptionPane.PLAIN_MESSAGE);
                    Ttextfield.setText(null);
               }
 
               try
               {
                    Rtextfield.setText(Double.toString(intrstArray[index-1]));
               }
 
               catch (NumberFormatException e)
               {
                    JOptionPane.showMessageDialog(null, "Invalid. try again!",
                                                       "Error", JOptionPane.PLAIN_MESSAGE);
                    Rtextfield.setText(null);
               }
          }
     }
 
     //calculation section
     void startCalculations()
     {
          Thread thisThread = Thread.currentThread();
          NumberFormat currency = NumberFormat.getCurrencyInstance();
 
          double amt = 0;
          double trm = 0;
          double intrst = 0;
          double moIn = 0;
          double moTrm = 0;
          double prin = 0;
          double paymt = 0;
 
          //amount error check
          try
          {
               amt = Double.parseDouble(Ltextfield.getText());
          }
 
          catch (NumberFormatException e)
          {
               JOptionPane.showMessageDialog(null, "Missing Amount",
                                             "Error", JOptionPane.PLAIN_MESSAGE);
               Ltextfield.setText(null);
               Ttextfield.setText(null);
               Rtextfield.setText(null);
               options.setSelectedIndex(0);
          }
 
          //term and interest error check
          try
          {
               trm = Double.parseDouble(Ttextfield.getText());
 
          }
 
          catch (NumberFormatException e)
          {
               JOptionPane.showMessageDialog(null, "missing Loan Term.  Please try again!",
                                                  "Error", JOptionPane.PLAIN_MESSAGE);
               Ttextfield.setText(null);
          }
 
          try
          {
               intrst = Double.parseDouble(Rtextfield.getText());
          }
 
          catch (NumberFormatException e)
          {
               JOptionPane.showMessageDialog(null, "missing Interest Rate.  Please try again!",
                                             "Error", JOptionPane.PLAIN_MESSAGE);
               Rtextfield.setText(null);
          }
 
          if (amt > 0)
          {
               amt = Double.parseDouble(Ltextfield.getText());
               moIn = (intrst / 1200);//monthly interest rate
               moTrm = trm * 12;//number of payments
               paymt = (amt * moIn) / (1-Math.pow((1+moIn), -moTrm));//amount forumla
                  yearlyPrinciple = new float[(int)trm]; // initialize the arrays to store yearly principle and interest
                  yearlyInterest = new float[(int)trm];
 
               $label.setText("" + currency.format(paymt));
 
               double newPrin = amt;
 
               for (int i = 0; i < trm; i++)
               {
                       yearlyInterest[i] = 0.0f;
                         yearlyPrinciple[i] = 0.0f;
                       for(int j = 1; j <=12; j++)
                         {
                    double newIn = moIn * newPrin;
                    double reduct = paymt - newIn;
                         yearlyInterest[i] += newIn;
                         yearlyPrinciple[i] += reduct;
                         newPrin = newPrin - reduct;
 
 
                    if (newPrin < 0)
                         newPrin = 0;
                    else
                         newPrin = newPrin;
 
 
                    model.addRow(new Object[] { Integer.toString((i*12) + j), currency.format(paymt),
                    currency.format(newIn), currency.format(reduct), currency.format(newPrin) });
                         }
 
 //                      model.addRow(new Object[] { Integer.toString(i), currency.format(0.0),
//                    currency.format(yearlyInterest[i]), currency.format(yearlyPrinciple[i]), currency.format(0.0) });
               }
          }
 
          //less than 0 error check
          if (amt < 0)
          {
               JOptionPane.showMessageDialog(null, "Please Enter Positie Numbers Only.",
                                             "Message Dialog", JOptionPane.PLAIN_MESSAGE);
               Ltextfield.setText(null);
          }
 
     }
 
     //resets all fields
     void reset()
     {
          Ltextfield.setText(null);
          Ttextfield.setText(null);
          Rtextfield.setText(null);
          options.setSelectedIndex(0);
          $label.setText(null);
          model.setRowCount(0);
     }
 
     //exit the program with thank you message
     void exit()
     {
          JOptionPane.showMessageDialog(null, "          Thank you ",
                                             "Message Dialog", JOptionPane.PLAIN_MESSAGE);
 
          System.exit(0);
     }
 
     public static void main(String args[])
     {
          java.awt.EventQueue.invokeLater(new Runnable()
          {
               public void run()
               {
                    new Mort6().setVisible(true);
               }
          });
     }
}
 
//creates class for container layout and placement
class Mort6Layout implements LayoutManager{
     public Mort6Layout() {}
 
     public void addLayoutComponent(String name, Component comp) {}
 
     public void removeLayoutComponent(Component comp) {}
 
     public Dimension preferredLayoutSize(Container parent)
     {
          Dimension dim = new Dimension(0, 0);
          Insets insets = parent.getInsets();
          dim.width = 600 + insets.left + insets.right;
          dim.height = 425 + insets.top + insets.bottom;
 
          return dim;
     }
 
     public Dimension minimumLayoutSize(Container parent)
     {
          Dimension dim = new Dimension(0, 0);
 
          return dim;
     }
 
     public void layoutContainer(Container parent)
     {
          Insets insets = parent.getInsets();
 
          Component c;
          c = parent.getComponent(0);
               if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+8,250,24);}
          c = parent.getComponent(1);
               if (c.isVisible()) {c.setBounds(insets.left+300,insets.top+8,175,24);}
          c = parent.getComponent(2);
               if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+40,250,24);}
          c = parent.getComponent(3);
               if (c.isVisible()) {c.setBounds(insets.left+300,insets.top+40,150,24);}
          c = parent.getComponent(4);
               if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+72,250,24);}
          c = parent.getComponent(5);
               if (c.isVisible()) {c.setBounds(insets.left+300,insets.top+72,96,24);}
          c = parent.getComponent(6);
               if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+104,250,24);}
          c = parent.getComponent(7);
               if (c.isVisible()) {c.setBounds(insets.left+300,insets.top+104,112,24);}
          c = parent.getComponent(8);
               if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+136,250,24);}
          c = parent.getComponent(9);
               if (c.isVisible()) {c.setBounds(insets.left+300,insets.top+136,112,24);}
          c = parent.getComponent(10);
               if (c.isVisible()) {c.setBounds(insets.left+50,insets.top+168,96,24);}
          c = parent.getComponent(11);
               if (c.isVisible()) {c.setBounds(insets.left+225,insets.top+168,112,24);}
          c = parent.getComponent(12);
               if (c.isVisible()) {c.setBounds(insets.left+400,insets.top+168,96,24);}
          c = parent.getComponent(13);
          if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+200,575,160);}
          c = parent.getComponent(14);
          if (c.isVisible()) {c.setBounds(insets.left+225,insets.top+375,112,24);}
     }
}
 
class GraphPanel extends JPanel
{
    final int
        HPAD = 60,
        VPAD = 40;
    int[] data;
    Font font;
     float[] principleData;
     float[] interestData;
 
 
    public GraphPanel(float[] p, float[] i)
    {
 
     principleData = p;
     interestData = i;
 
        font = new Font("lucida sans regular", Font.PLAIN, 16);
        setBackground(Color.white);
    }
 
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
 
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        int w = getWidth();
        int h = getHeight();
        // scales
        float xInc = (w - HPAD - VPAD) / (interestData.length - 1);//11f;
        float yInc = (h - 2*VPAD) / 10f;
        int[] dataVals = getDataVals();        //min and max values for y-axis
        float yScale = dataVals[2] / 10f;
 
        // ordinate (y - axis)
        g2.draw(new Line2D.Double(HPAD, VPAD, HPAD, h - VPAD));
        // plot tic marks
        float x1 = HPAD, y1 = VPAD, x2 = HPAD - 3, y2;
        for(int j = 0; j < 10; j++)
        {
            g2.draw(new Line2D.Double(x1, y1, x2, y1));
            y1 += yInc;
        }
        // labels
        String text; LineMetrics lm;
        float xs, ys, textWidth, height;
        for(int j = 0; j <= 10; j++)
        {
            text = String.valueOf(dataVals[1] - (int)(j * yScale));
            textWidth = (float)font.getStringBounds(text, frc).getWidth();
            lm = font.getLineMetrics(text, frc);
            height = lm.getAscent();
            xs = HPAD - textWidth - 7;
            ys = VPAD + (j * yInc) + height/2;
            g2.drawString(text, xs, ys);
        }
 
        // abcissa (x - axis)
        g2.draw(new Line2D.Double(HPAD, h - VPAD, w - VPAD, h - VPAD));
        // tic marks
        x1 = HPAD; y1 = h - VPAD; y2 = y1 + 3;
        for(int j = 0; j < interestData.length; j++)
        {
            g2.draw(new Line2D.Double(x1, y1, x1, y2));
            x1 += xInc;
        }
        // labels
        ys = h - VPAD;
        for(int j = 0; j < interestData.length; j++)
        {
            text = String.valueOf(j + 1);
            textWidth = (float)font.getStringBounds(text, frc).getWidth();
            lm = font.getLineMetrics(text, frc);
            height = lm.getHeight();
            xs = HPAD + j * xInc - textWidth/2;
            g2.drawString(text, xs, ys + height);
        }
 
        // plot data
          float yy2 = 0, yy1 = 0, xx2 = 0, xx1;
        x1 = HPAD;
          xx1 = HPAD;
        yScale = (float)(h - 2*VPAD) / dataVals[2];
 
        for(int j = 0; j < interestData.length; j++)
        {
          g.setColor(Color.blue);
          y1 = VPAD + (h - 2*VPAD) - (principleData[j] - dataVals[0]) * yScale;
 
            if(j > 0)
            g2.draw(new Line2D.Double(x1, y1, x2, y2));
            x2 = x1;
            y2 = y1;
            x1 += xInc;
 
          g.setColor(Color.red);
          yy1 = VPAD + (h - 2*VPAD) - (interestData[j] - dataVals[0]) * yScale;
               if(j > 0)
            g2.draw(new Line2D.Double(xx1, yy1, xx2, yy2));
            xx2 = xx1;
            yy2 = yy1;
            xx1 += xInc;
 
        }
    }
 
    private int[] getDataVals()
    {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
          int j = interestData.length -1;
          max = (int)principleData[j];
          min = (int)interestData[j];
        int span = max - min;
        return new int[] { min, max, span };
    }
}

Open in new window

pink16Asked:
Who is Participating?
 
fsze88Commented:
as it is package week5, external file should located in C:\Prg421.
also you run this package from C:\Prg421>java Week5.Mort6
0
 
objectsCommented:
You need to run it from the directory that contains file

Or change code to

InputSTream in = getClass().getResourceAsStream("data.txt");
0
 
avdejCommented:
Here are two easy solutions for your issue:

I. The shortest (not the best) way to get your program running:

1. Replace line 96 in your code with the following code snippet (just copy/paste it)::

fis = new FileReader
(
    System.getProperty("java.class.path")
    + File.separator
    + "Week5"
    + File.separator
    + "data.txt"
);

2. Then you MUST run your program with the following command line:
    $>java -cp C:\Prg421 Week5.Mort6

Explanation:
Because you explicitly set the classpath value to the single entry (C:\Prg421) you can get it later
by means of system property "java.class.path" and use it as a root directory for further file navigation.
To run your program with the command line above you don't need to navigate from a command console
to some certain directory -- you can call it staying anywhere in a file structure.

II. The better (i.e. more flexible) way to accomplish the task of reading data file
    is to provide the file location as a command line parameter:
1. Add the field to your class:
    String dataPath = null;
2. Place the following line within your main() method:
   dataPath = args[0];
3. Change line 96 to:
   fis = new FileReader(dataPath);
4. Call your program with the following command line:
    C:\Prg421>java Week5.Mort6 C:\Prg421\Week5\data.txt
5. Your data file can be stored at some arbitrary location as you provide it every time as a line parameter

Avdej
0
 
nkiggsCommented:
Compile your application with the destination folder to host your class file in the current directory (-d .). Then execute the file Mort6 in the package Week5 (java -cp .  Week5.Mort6)

C:\Prg421\Week5>javac -d . *.java

C:\Prg421\Week5>java -cp .  Week5.Mort6
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.