troubleshooting Question

How do I create a data.text file for my program?

Avatar of omoa
omoa asked on
Java
12 Comments1 Solution416 ViewsLast Modified:
I feel I am hitting my head against a wall.  I am sure it is something simple I am missing because I can figure out the hard parts however the simplest things get me everytime. I am using TextPad. to compile my program.  My below program will compile but nothing but errors display in the  C:\WINDOWS\SYSTEM\32\cmd.exe  . It starts with this error:
java. io.FILENOTFOUNDESCEPTION:data.text ( The system cannot find the file specified).
 
I understand that I need to create a data.text file but am lost as to how to create such a file. Can you provide me an example of what I need to create in order to make my program work correctly? Any insight would be helpful.

My code:

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;



import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;




public class mortCalcWk5 extends JFrame implements ActionListener {



   //adding initial selection options via RadioButtons
   JPanel row1a = new JPanel();
   JRadioButton option1 = new JRadioButton("Manual Input", true);
   JRadioButton option2 = new JRadioButton("Menu Selections", false);

   //content Buttons, Panels, Labels, and TextFields
   JPanel row1 = new JPanel();
   JLabel principalLabel = new JLabel();

   JTextField loanField = new JTextField(15);
   JLabel loan2Label = new JLabel();
   JPanel row2 = new JPanel();

   JPanel row2a = new JPanel();
   JLabel termLabel = new JLabel();  //term
   JTextField termField = new JTextField(7);

   JPanel row2b = new JPanel();
   JLabel interestEntryLabel = new JLabel();  //interest
   JTextField interestEntryField = new JTextField(7);

   JComboBox options = new JComboBox();
   JLabel optionsLabel = new JLabel();

   JPanel row3 = new JPanel();
   JButton calculateButton = new JButton();
   JButton resetButton = new JButton();
   JButton exitButton = new JButton();

   JPanel row4 = new JPanel();
   JLabel paymentLabel = new JLabel();
   JTextField paymentField = new JTextField(15);

   JPanel row5= new JPanel();
   JLabel outputLabel = new JLabel();

   JPanel row6 = new JPanel();
   JTextArea openField = new JTextArea(25,55);


   JScrollPane scrollPane = new JScrollPane(openField,
        ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

   ButtonGroup radioSelect = new ButtonGroup();
   JTable table;//create table
       DefaultTableModel model;//table model
       int[] termArray;
       double[] interestArray;
       JButton graph;
       private float[]  yearlyPrinciple;
       private float[]  yearlyInterest;
       private JComboBox  jComboBoxOptions;



   //setting format of GUI layout
     public mortCalcWk5() {

      //main GUI Dimensions
      super(" McBride Financial Services Mortgage Calculator");
      setSize(700,650);
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      load();
      init();
      pack();

      setVisible(true);

    }

     //reading from sequential file
     public void load()
     {
          Reader fis;
               try
               {
                    fis = new FileReader("data.txt");

                    BufferedReader b = new BufferedReader( fis );

                    String[] line = b.readLine(  ).split(",");
                    termArray = new int[line.length];
                    for ( int i = 0; i < line.length; i++ )
                    {
                         termArray[ i ] = Integer.parseInt(line[i].trim());
                    }

                    line = b.readLine(  ).split(",");
                    interestArray = new double[line.length];
                    for ( int i = 0; i < line.length; i++ )
                    {
                         interestArray[ i ] = Double.parseDouble(line[i].trim());
                    }

               b.close();
               fis.close();
               }

               catch ( Exception e1 )
               {
                    e1.printStackTrace(  );
               }
     }

  public void init()
     {
              Mortgage5Layout customLayout = new Mortgage5Layout();
              Container con = getContentPane();
          con.setLayout(customLayout);

      //layout for mortgage amount entry
       principalLabel.setText("Enter Amount Borrowed:$(no comma)");
      row1.add(principalLabel);
      row1.add(loanField);
      getContentPane().add(row1);


      radioSelect.add(option1);
      radioSelect.add(option2);
      row1a.add(option1);
      row1a.add(option2);
      con.add(row1a);


      //layout for options
      options.addItem(" (choose rate)");
      options.addItem("7 years at 5.35%");
      options.addItem("15 years at 5.5%");
      options.addItem("30 years at 5.75%");
      options.setEnabled(false);


      row2.add(options);
      con.add(row2);


      termLabel.setText("Term in Years");
      row2a.add(termLabel);
      row2a.add(termField);
      con.add(row2a);


      interestEntryLabel.setText("Interest %");
      row2b.add(interestEntryLabel);
      row2b.add(interestEntryField);
      con.add(row2b);

      //layout for buttons to calculate, Reset, and EXIT

      calculateButton.setText("Calculate Payment");
      row3.add(calculateButton);
      resetButton.setText("Reset Calcutor");
      row3.add(resetButton);
      exitButton.setText("Exit Program");
      row3.add(exitButton);
      con.add(row3);

      //layout for section that shows the monthly payment amount
      paymentLabel.setText("Monthly Payment Amount:");
      row4.add(paymentLabel);
      row4.add(paymentField);
      con.add(row4);

      //layout for loan amoritzation table
      outputLabel.setHorizontalAlignment(SwingConstants.CENTER);
      outputLabel.setVerticalAlignment(SwingConstants.BOTTOM);
      outputLabel.setText("Loan Amoritization Table");
      outputLabel.setHorizontalTextPosition(SwingConstants.CENTER);
      row5.add(outputLabel);
      con.add(row5);

      openField.setLineWrap(true);
      openField.setWrapStyleWord(true);
      openField.setEditable(true);
      row6.add(scrollPane);
      con.add(row6);

     //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 ("Display Graph");//Display Graph button
   con.add(graph);


      //setting actionListeners for Fields and Buttons
      loanField.addActionListener(this);
      options.addActionListener(this);
      termField.addActionListener(this);
      interestEntryField.addActionListener(this);
      calculateButton.addActionListener(this);
      resetButton.addActionListener(this);
      exitButton.addActionListener(this);
      option1.addActionListener(this);
      option2.addActionListener(this);
      graph.addActionListener(this);  //graphButton
   }


//adding actionEvents for Buttons
   public void actionPerformed(ActionEvent event) {

      Object source = event.getSource();

            //set Calculation button
      if (source == calculateButton) {
         startCalculations();
      }

      // set Reset button
      if (source == resetButton) {
         reset();
      }

      //sets exit button
      if (source == exitButton) {
         exit();
      }
            // set manual input button
      if (source == option1){

         options.setEnabled(false);
         termField.setEnabled(true);
         termField.setEditable(true);
         interestEntryField.setEnabled(true);
         interestEntryField.setEditable(true);
         paymentField.setEditable(false);


      }
            // set Menu Seletion button
      if (source == option2){

         options.setEnabled(true);
         termField.setEnabled(false);
         termField.setEditable(false);
         interestEntryField.setEnabled(false);
         interestEntryField.setEditable(false);
             paymentField.setEditable(false);


      }//end component construction

   }// end action event for buttons



//formulas for monthly payment
   void startCalculations() {

      Thread thisThread = Thread.currentThread();
      NumberFormat currency = NumberFormat.getCurrencyInstance();

//varibles used
      double amount = 0;   //amount of loan
      double term = 0;   //variable for term of loan
      double interest = 0;  //variable for interest amount of loan
      double monthlyInterest = 0;  //variable for monthly payment for formula
      double monthlyTerm = 0; //variable for monthly term for formula
      double principal; // variable for principle
      double payment = 0;  //variable for payment

      boolean Exception = false;

//exception used to catch invalid data in loan field
      try {
         amount = Double.parseDouble(loanField.getText());
      } catch (NumberFormatException e) {
         JOptionPane.showMessageDialog(null,"Please re-enter a valid Loan Amount without commas",
                 "Principal Amount Error", JOptionPane.ERROR_MESSAGE);
         loanField.setText(null);
         interestEntryField.setText(null);
      }
// Pre-loaded term and interest data for menu selections
      if (option2.isSelected()) {
         if(options.getSelectedIndex() == 0) {
            term=7;
            interest=5.35;
         } else if(options.getSelectedIndex() ==1) {
            term=15;
            interest=5.5;
         } else {
            term=30;
            interest=5.75;
         } // end if

      } //end if

      //loan information retrieval for manual input options
      else {
        // exception used to catch invalid data in the term field
         try {
            term = Double.parseDouble(termField.getText());
            if (term < 0) {
                  throw new NumberFormatException();
            }
              } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null,"Enter a positive number higher than zero.","Loan Terms in Years Error",JOptionPane.ERROR_MESSAGE);
            Exception=true;
            termField.setText(null);
         }// end catch

    // exception used to catch invalid data in the intrest field
         try {
            interest= Double.parseDouble(interestEntryField.getText());
            if (interest < 0) {
                  throw new NumberFormatException();
            }
         } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null,"Re-enter a positive Interest Rate using a(0.00)format","Interest Amount Error",JOptionPane.ERROR_MESSAGE);
            Exception=true;
            interestEntryField.setText(null);

         }
      }// end catch


//output for Loan Amoritzation Table
      if (amount >0 && !Exception) {
         amount = Double.parseDouble(loanField.getText());
   //  formula used to calculate monthly interest
         monthlyInterest  = (interest / 12) / 100;
   // formula used to calculate montly terms for loan
         monthlyTerm = term * 12;  //

 //formula used to calculate monthly payment
         payment = amount * (monthlyInterest  / (1 -Math.pow((1 + monthlyInterest ), (-monthlyTerm))));
//Dispay monthly payment
         paymentField.setText("" + currency.format(payment));


// headers used in open field display for amortization
         openField.append("Payment# Made");
         openField.append("      ");
         openField.append("         Monthly Payment");
         openField.append("       ");
         openField.append("         Interest Paid");
         openField.append("      ");
         openField.append("          Reduction");
         openField.append("      ");
         openField.append("       New Balance");
         openField.append("      \n");
         double newPrincipal = amount;

// loop for amortization table
         for (int i = 1; i <= monthlyTerm; i++) {
// formula used to display amount of interest paid
            double newInterest = monthlyInterest  * newPrincipal;
// formula used to display amount of reduction in principal
            double reduct = payment - newInterest;
// formula used to display new balance on loan
            newPrincipal = newPrincipal - reduct;

//displays data from the above formulas into amorzation table
            openField.append("        " + i);
            openField.append("\t               " + currency.format(payment));
            openField.append("\t     " + currency.format(newInterest));
            openField.append("\t             " + currency.format(reduct));
            openField.append("         " + currency.format(newPrincipal) + "\n");

      if((amount <= 0 || term <= 0 || interest <= 0) && (Exception == false)) {
               JOptionPane.showMessageDialog(null, "Please Enter Positive Numbers Only.",
                  "Error Message", JOptionPane.ERROR_MESSAGE);
               if(amount <= 0)
                  loanField.setText(null);
                  termField.setText(null);
            }
         }
      }
   }

   // private class used block everything except a postive number in interest field
   private class PositiveDoubleDocument extends PlainDocument {
      public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
      {
         StringBuilder sb = new StringBuilder(getText(0, getLength()));
         sb.insert(offs, str);
         try {
            double data = Double.parseDouble(sb.toString());
            if (data >= 0) {
               super.insertString(offs, str, a);
            }
         } catch (NumberFormatException e) {

         }//end try

      }// end catch

   }//end private class

// resets GUI for another calculation
   void reset() {

      loanField.setText(null);
      paymentField.setText(null);
      openField.setText(null);
      termField.setText(null);
      interestEntryField.setText(null);
   }

// ends GUI and exits program
   void exit() {
      System.exit(0);
   }


//main method to close program
   public static void main(String args[]){
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run(){
            new mortCalcWk5().setVisible(true); }});

   }
}
//creates class for container layout and placement
class Mortgage5Layout implements LayoutManager{
     public Mortgage5Layout() {}

     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;  //distance between each plot
        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 };
    }
}
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 12 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 12 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros