Solved

Create Array with variable input from user

Posted on 2004-09-11
5
420 Views
Last Modified: 2012-05-05
I am new to the JAVA language and have a problem of converting code input from the user to be used in setting up an array. The field will be used as part of the array data. CODE is below and commented where I need help. Urgent timeline required.

/*
  Name:        Rick Powell - Team D
  Project:      Mortgage Payment Program
  Class:        POS 407 - Programming II
  Week:        Week 4 Mortgage Menu Selection Assignment
  File:           MortgageCalcMRP.java
  Version:   3.6.8
  Purpose:       This GUI program is used to calculate the monthly mortgage payment
                   for the user when proper input made. This can be used to evaulate different mortgage
                   rates form multiple financial institutions.

*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;

public class MortgageCalcMRP extends JPanel
    {
        public int arraynum=0;
        public  boolean paymentZeroFlag = true;      //   Flag for zero amount in screen field for monthly payment amount
             // Button and Radio Button defintions.
             public JButton resetButton;
             public JButton calculateButton;
             public JButton quitButton;
             public JButton reportButton;
        public  JRadioButton rate1Button = new JRadioButton("Rate 1 - 7 years at 5.25%   (84 Monthly Payments)");
        public  JRadioButton rate2Button = new JRadioButton("Rate 2 - 15 years at 5.50%  (180 Monthly Payments)");
        public  JRadioButton rate3Button = new JRadioButton("Rate 3 - 30 years at 5.75%  (360 Monthly Payments)");
        public  JRadioButton rate4Button = new JRadioButton("Enter Information Manually");
            //Labels for the input fields.
             public JLabel amountLabel = new JLabel("Loan Amount: ",JLabel.RIGHT);
             public JLabel rateLabel = new JLabel("Interest Rate:  " ,JLabel.RIGHT );
             public JLabel yearsTermLabel = new JLabel("Years of Term: ",JLabel.RIGHT);
             public JLabel paymentLabel = new JLabel("Monthly Payment: ",JLabel.RIGHT);
             public JLabel filler1Label = new JLabel(" ",JLabel.CENTER);
             public JLabel filler2Label = new JLabel(" ",JLabel.CENTER);
             public JLabel filler3Label = new JLabel(" ",JLabel.CENTER);
             public JLabel filler4Label = new JLabel("  ",JLabel.CENTER);
             //Text fields for data entry
             public JTextField loanAmountField;
             public JTextField interestRateField;
             public JTextField yearsTermField;
             public JTextField paymentField;
        public JTextArea dataReportArea;
             // Formats for entered data.
             public DecimalFormat decimalFormat =      (DecimalFormat) NumberFormat.getNumberInstance();
             public NumberFormat currencyFormat =       (NumberFormat) NumberFormat.getNumberInstance();
             public NumberFormat percentFormat = NumberFormat.getNumberInstance();
             public DecimalFormat paymentFormat =            (DecimalFormat) NumberFormat.getNumberInstance();
             public DataVerifier verifier = new DataVerifier();
             // Execute the constructor.
             public MortgageCalcMRP()
                 {
                         super(new BorderLayout());
                         // Formatting for display purposes of payment data.
                         percentFormat.setMinimumFractionDigits(3);
                         decimalFormat.setParseIntegerOnly(true);
                         paymentFormat.setMaximumFractionDigits(2);
                         paymentFormat.setNegativePrefix("(");
                         paymentFormat.setNegativeSuffix(")");
                         double payment = 0.00;
                         //Create the text fields and set them up.
                         loanAmountField = new JTextField(currencyFormat.format(0.00), 10);
                         loanAmountField.setInputVerifier(verifier);
               loanAmountField.setBackground(Color.yellow);
                         interestRateField = new JTextField(percentFormat.format(0.00), 10);
                         interestRateField.setInputVerifier(verifier);
               interestRateField.setEditable(false);
                         yearsTermField = new JTextField(decimalFormat.format(0), 10);
                         yearsTermField.setInputVerifier(verifier);
               yearsTermField.setEditable(false);
                         paymentField = new JTextField(paymentFormat.format(0.00), 10);
                         paymentField.setInputVerifier(verifier);
                         paymentField.setEditable(false);
               //  Create text area to output data report
               filler1Label.setForeground(Color.red);  //  Set text color red for error highlites
               filler2Label.setForeground(Color.red);
               filler3Label.setForeground(Color.red);
               filler4Label.setForeground(Color.red);
               dataReportArea = new JTextArea(5, 60);
               dataReportArea.setEditable(false);
               dataReportArea.setForeground(Color.gray);
               dataReportArea.setFont(new Font("Fixedsys", Font.BOLD,12));
               JScrollPane scrollPane = new JScrollPane(dataReportArea,  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
               // Create radio buttons for rate selections
               rate1Button.setSelected(false);
               rate1Button.addItemListener(new SelectItemListener());
                    rate2Button.addItemListener(new SelectItemListener());
               rate3Button.addItemListener(new SelectItemListener());
               rate4Button.addItemListener(new SelectItemListener());
               rate1Button.setBackground(Color.green);
               rate2Button.setBackground(Color.green);
               rate3Button.setBackground(Color.green);
               rate4Button.setBackground(Color.white);
               //  Group the radio buttons for one selection.
               ButtonGroup groupRate = new ButtonGroup();
                                                                                     groupRate.add(rate1Button);
                                                                                     groupRate.add(rate2Button);
               groupRate.add(rate3Button);
               groupRate.add(rate4Button);
                // Set the button text.
                         resetButton = new JButton("Reset Data Fields");
               resetButton.setBackground(Color.blue);
               resetButton.setForeground(Color.white);
                         calculateButton = new JButton("Calculate Mortgage");
               calculateButton.setBackground(Color.red);
               calculateButton.setForeground(Color.white);
                         quitButton = new JButton("Quit Program");
               quitButton.setBackground(Color.black);
               quitButton.setForeground(Color.white);
                         reportButton = new JButton("Create Report");
               reportButton.setBackground(Color.white);
               reportButton.setForeground(Color.red);
                         //Register an action listener.
                         loanAmountField.addActionListener(verifier);
                         interestRateField.addActionListener(verifier);
                         yearsTermField.addActionListener(verifier);
                         resetButton.addActionListener(verifier);
                         calculateButton.addActionListener(verifier);
                         quitButton.addActionListener(verifier);
                         reportButton.addActionListener(verifier);
                         //Set the label values.
                         amountLabel.setLabelFor(loanAmountField);
                    rateLabel.setLabelFor(interestRateField);
                    yearsTermLabel.setLabelFor(yearsTermField);
                         paymentLabel.setLabelFor(paymentField);
                         //Lay out the labels in a panel.
               Border raisedetched;
               raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
                         JPanel labelPane = new JPanel(new GridLayout(0,1));
               labelPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
                    labelPane.add(amountLabel);
                    labelPane.add(rateLabel);
                    labelPane.add(yearsTermLabel);
                    labelPane.add(paymentLabel);
                         labelPane.add(filler1Label);
                         labelPane.add(filler2Label);
                         labelPane.add(filler3Label);
                         labelPane.add(filler4Label);
                         //Layout the text fields in a panel.
                         JPanel fieldPane = new JPanel(new GridLayout(0,1));
               fieldPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
                         fieldPane.add(loanAmountField);
                         fieldPane.add(interestRateField);
                         fieldPane.add(yearsTermField);
                         fieldPane.add(paymentField);
                         fieldPane.add(calculateButton);
                         fieldPane.add(resetButton);
                         fieldPane.add(reportButton);
                         fieldPane.add(quitButton);
               // Create etched borders for panels
                        JPanel textPane = new JPanel(new GridLayout(0, 1));
               textPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
                         textPane.add(scrollPane);
               // Create radio button for 3 preset loan rates/terms and add border
                         JPanel radioPane  = new JPanel(new GridLayout(0, 1));
               radioPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
                         radioPane.add(rate1Button);
                         radioPane.add(rate2Button);
                         radioPane.add(rate3Button);
                         radioPane.add(rate4Button);
                         //Put the labels on left, entry fields on right.
                         setBorder(BorderFactory.createEmptyBorder(10,40,40, 40));     //    (TOP, LEFT, BOTTOM, RIGHT)
                         add(labelPane, BorderLayout.CENTER);
                         add(fieldPane, BorderLayout.LINE_END);
                         add(textPane, BorderLayout.SOUTH);
                         add(radioPane, BorderLayout.WEST);
                 }  //  End MortgageCalcMRP method block
             // This class will test for the performed actions, and execute the
             // method for calculating the payment.
             class DataVerifier extends InputVerifier implements ActionListener
                 {
                   public void actionPerformed(ActionEvent e)
                            {
                                    Object selected = e.getSource();
                                     //  Clear the fields from user data and report area.
                                     if (selected == resetButton)
                                        {
                                                loanAmountField.setText(paymentFormat.format(0.00));
                                                paymentField.setText(paymentFormat.format(0.00));
                            dataReportArea.setText("  \n");
                            paymentZeroFlag = true;
                              }
                                     // Calculate mortgage payment.
                                     if (selected == calculateButton)
                                        {
                                                getPayment();
                                        }
                                     // Quit Program
                                    if (selected == quitButton)
                                        {
                                                System.exit(0);
                                        }
                                                       // Create Report for screen output
                                    if (selected == reportButton)
                                        {
                         if (paymentZeroFlag == false)
                         {
                                 NumberFormat formatMonthNum = new DecimalFormat("   000");               //   Column formatter for payment number
                                      NumberFormat formatpercent = new DecimalFormat(".00");                                   //   Percent Rate formatter for payment number
                                      String formatStartBalance, formatInterest, formatPrincipal, formatEndBalance, formatPayment;      // Format display for column data
                            dataReportArea.setText("Payment            Month              Start Balance           Interest             Principal           End Balance \n");
                            double principal =  Double.parseDouble( loanAmountField.getText());            //  Principal to finance
/*     NEED HELP HERE
      I need to convert the text field interestRateField to a double number
     so I can use it in the array below. I hardcoded the vairable ratePercentManual
     which I need convert to a double number. This will represent the users choice
     of the rate perrentage
*/
                            double ratePercentManual = 7.5f;
//  Above line code temp
                                 double ratePercent[] = { 5.35f, 5.50f, 5.75f, (ratePercentManual) };                                                  //   rate of loan
                                 double rate[] =             {       ratePercent[0]/100.00,                         ratePercent[1]/100.00,       ratePercent[2]/100.00,  ratePercent[3]/100.00       };      // rate in decimal format percentage

/*     NEED HELP HERE
      I need to convert the text field yearsTermField to an integer number
     so I can use it in the array below. I hardcoded the vairable yearsLoanManual
     which I need convert to an integer number. This will represent the users choice
     of the rate perrentage
*/
                            int yearsLoanManual = 20;
//  Above line code temp
                            int yearsLoan[] =   {  7,  15, 30, (yearsLoanManual) };                                                                         //   Number of years for loan

                            int paymentsPerYear = 12;                                                                                            //   Set 12 month per year constant
                                 int numPayments[] = { paymentsPerYear * yearsLoan[0],  paymentsPerYear * yearsLoan[1],  paymentsPerYear * yearsLoan[2],  paymentsPerYear * yearsLoan[3]  };      // number of payments for loan
                                 double effectiveAnnualRate[] =      { rate[0] / paymentsPerYear,       rate[1] / paymentsPerYear, rate[2] / paymentsPerYear, rate[3] / paymentsPerYear            };      // variable percentage rate of loan
                                 double payment[] =      { principal*(effectiveAnnualRate[0] / (1 - Math.pow(1 + effectiveAnnualRate[0], -numPayments[0]))),
                                                                      principal*(effectiveAnnualRate[1] / (1 - Math.pow(1 + effectiveAnnualRate[1], -numPayments[1]))),
                                                                      principal*(effectiveAnnualRate[2] / (1 - Math.pow(1 + effectiveAnnualRate[2], -numPayments[2]))),
                                                                      principal*(effectiveAnnualRate[3] / (1 - Math.pow(1 + effectiveAnnualRate[3], -numPayments[3])))
                                                                      }; //calculates montly payment
                            int counter = 1;                                                                                                                                //   loop counter
                            int payNumber = 0;                                                                                                                    //   payment increment counter
                            double startBalance      = principal;                                                                                 //   starting balance for display output
                            double endBalance = 0.0;                                                                                                    //   ending balance for display output
                            double paidInterest = 0.0;                                                                                                     //   paid interest for display output
                            double paidPrincipal = 0.0;                                                                                                   //   paid interest for display output
                                           int startYear = 2004;                                                                                                            //   year to start payments
                                           int payYear = startYear;                                                                                                 //   year counter for output column display
                                           int startMonth = 9;                                                                                                                     //   month to start first payment
                                           int payMonth = startMonth;                                                                                         //  actual pay month for each payment
                                      String  month = "   ";                                                                                                                  //  string format for month payment
                                      formatPayment = formatColumn(payment[arraynum]);
                                      while (payNumber < numPayments[arraynum])                                //   Start main loop and exit if (q) or (Q) keys selected or last payment displayed
                                {
                                   payNumber++;                                                                                                                                                       //   Payment number in table
                                                       month = formatMonthDate(payMonth)+payYear;                                           //   Format month payment display
                                                       if (payMonth == 12) {payYear++; payMonth=0;}                                           //   If payment month is Dec start next payment in month of Jan
                                                                     paidInterest = ((startBalance*rate[arraynum])/12);                          //   Interest paid on principal balance
                                                           paidPrincipal  = (payment[arraynum]-paidInterest);                                   //   Principal paid on loan
                                                           endBalance  = (startBalance-paidPrincipal);                                                        //   End balance after intrerest & principal applied toward balance
                                                                     formatStartBalance = formatColumn(startBalance);                                  //   Format data for even columns
                                                                     formatInterest = formatColumn(paidInterest);
                                                                     formatPrincipal = formatColumn(paidPrincipal);
                                                                     formatEndBalance = formatColumn(endBalance);
                                            //  Print a line of data from table
                                            dataReportArea.append(formatMonthNum.format(payNumber)+"\t"+(month)+"\t"+formatStartBalance+"\t"+formatInterest+"\t"+formatPrincipal+"\t"+formatEndBalance+"\n\n");
                                       payMonth++;
                                            if (endBalance > 0.0)                                                      // If not last payment set start balance to previous ending balance
                                                     startBalance = endBalance;
                                               }
                                                                                                                                                                  }  //  End paymentFlagZero check block
                                        }  //  End Report Output
                            }   // End actionPerformed block
                         // Verify that the input data is valid, then calculate the mortgage.
                        protected void getPayment()
                            {
                     // initialize values to 0
                                    double amount = 0.00;
                                    double rate = 0.00;
                                    int numPeriods = 0;
                                    double payment = 0.0;
                                    // Parse the input values.  If an exception occurs, set the fields default value of 0.
                                    try
                                       { amount = currencyFormat.parse(loanAmountField.getText()).doubleValue(); }
                                    catch (Exception e)
                                       {       loanAmountField.setText(paymentFormat.format(0.00)); }
                                    try
                                       { rate = percentFormat.parse(interestRateField.getText()).doubleValue(); }
                                    catch (Exception e)
                                       {       interestRateField.setText(paymentFormat.format(0.00));      }
                                    try
                                       { numPeriods =      decimalFormat.parse(yearsTermField.getText()).intValue(); }
                                    catch (Exception e)
                                       { yearsTermField.setText(paymentFormat.format(0.00)); }
                                    // Calculate the mortgage  and update the monthly payment.
                                    payment = calculatePayment(amount, rate, numPeriods);
                     //  Used to set flag for display report data. If valid data flag is false else flag is true
                     if (payment >= 0.000000001)
                         {paymentZeroFlag = false;}
                     else
                         {paymentZeroFlag = true;}
                                    paymentField.setText(paymentFormat.format(payment));
                            }
                        // Check the input.
                        public boolean verify(JComponent input)
                            {
                                    return true;
                       }
                 }  //  End class DataVerifier block
          //  Used to create report column formatted data
          public static String formatColumn(double floatNumber)
                         {
                             DecimalFormat numberFormat = new DecimalFormat("$#,##0.00");
                        String stringOfNum = numberFormat.format(floatNumber);
                        int numLen = stringOfNum.length();
                             if (numLen < 13) stringOfNum = "            ".substring(numLen) + stringOfNum;
                             return (stringOfNum);
                    }
          //  Used to format the month data for report
               public static String formatMonthDate(int payMonth)
                         {
                                  String month = "   ";
                                  switch (payMonth)
                                             {
                                                        case 1:  month = "01 JAN "; break;
                                                        case 2:  month = "01 FEB "; break;
                                                        case 3:  month = "01 MAR "; break;
                                                        case 4:  month = "01 APR "; break;
                                                        case 5:  month = "01 MAY "; break;
                                                        case 6:  month = "01 JUN "; break;
                                                        case 7:  month = "01 JUL "; break;
                                                        case 8:  month = "01 AUG "; break;
                                                        case 9:  month = "01 SEP "; break;
                                                        case 10: month = "01 OCT "; break;
                                                        case 11:      month = "01 NOV "; break;
                                                        case 12: month = "01 DEC "; break;
                                                        default: month = "   ";
                                        }
                             return (month);
                    }
        // Routine for Radio Button selection and action
        class  SelectItemListener implements ItemListener
              {
                        public void itemStateChanged(ItemEvent e)
                            {
                          // Get object
                          AbstractButton sel = (AbstractButton)e.getItemSelectable();
                                    // Checkbox select or not
                                    if(e.getStateChange() == ItemEvent.SELECTED)
                                        {
                                           if (sel.getText().equals("Rate 1 - 7 years at 5.25%   (84 Monthly Payments)"))
                                               {
                                          paymentZeroFlag = true;
                                          System.out.println("7 year loan at 5.25% selected");           // Debug purposes only
                                          arraynum = 0;  //  Selection rate1RadioButton used for array number 1
                                                              yearsTermField.setText("7");
                                                         interestRateField.setText("5.25");
                                                              paymentField.setText("0.00");
                                         dataReportArea.setText("  \n");
                                          interestRateField.setEditable(false);
                                          yearsTermField.setEditable(false);
                                     }
                                 else if (sel.getText().equals("Rate 2 - 15 years at 5.50%  (180 Monthly Payments)"))
                                          {
                                          paymentZeroFlag = true;
                                          System.out.println("15 year loan at 5.50% selected");         // Debug purposes only
                                          arraynum = 1;  //  Selection rate2RadioButton used for array number 2
                                                         yearsTermField.setText("15");
                                                    interestRateField.setText("5.50");
                                                         paymentField.setText("0.00");
                                         dataReportArea.setText("  \n");
                                          interestRateField.setEditable(false);
                                          yearsTermField.setEditable(false);
                                     }
                                 else if (sel.getText().equals("Rate 3 - 30 years at 5.75%  (360 Monthly Payments)"))
                                           {
                                          paymentZeroFlag = true;
                                          System.out.println("30 year loan at 5.75% selected");           // Debug purposes only
                                                                                                                               arraynum = 2;  //  Selection rate3RadioButton used for array number 3
                                                         yearsTermField.setText("30");
                                                    interestRateField.setText("5.75");
                                                         paymentField.setText("0.00");
                                         dataReportArea.setText("  \n");
                                          interestRateField.setEditable(false);
                                          yearsTermField.setEditable(false);
                                          }
                                else if (sel.getText().equals("Enter Information Manually"))
                                           {
                                          paymentZeroFlag = false;
                                          System.out.println("Enter Information Manually");           // Debug purposes only
                                                                                                                               arraynum = 3;  //  Selection rate3RadioButton used for array number 4
                                                         yearsTermField.setText("0");
                                                    interestRateField.setText("0.0");
                                                         paymentField.setText("0.00");
                                         dataReportArea.setText("  \n");
                                          interestRateField.setEditable(true);
                                          yearsTermField.setEditable(true);
                                          }
                              }  //  End ItemSelected block
                       }  //  End ItemStateChanged
              }  //  End SelectItemListner block
             // Compute the monthly payment based on the loan amount,
             // APR, and length of loan.  I seem to remember doing something similiar to
             // this is in a past class.
             public double calculatePayment(      double loanAmt, double rate, int numPeriods)
                {
                        double monthlyPayment = 0;
                        double monthlyInterestRate = (rate / 100 / 12);
                        numPeriods *= 12;
                        monthlyPayment =      ((loanAmt * Math.pow((1 + monthlyInterestRate), numPeriods))
                                                        * monthlyInterestRate)            / (Math.pow((1 + monthlyInterestRate), numPeriods) - 1);
                        return monthlyPayment;
                }
        // main program block
             public static void main(String[] args)
                 {
                    //Create and set up the window.
                    JFrame frame = new JFrame("My Mortgage Calculator");
                         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                         //Create and set up the content pane.
                         JComponent newContentPane = new MortgageCalcMRP();
                         newContentPane.setOpaque(true);
                         frame.setContentPane(newContentPane);
                         //Display the window.
                         frame.pack();
                         frame.setVisible(true);
                 }  //  End main program block
   }  //  End MortgageMRP class
0
Comment
Question by:RICKPOWELL1955
  • 2
5 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 12035112
You need to replace the following commented out lines thus:


//double ratePercentManual = 7.5f;
double ratePercentManual = Double.parseDouble(interestRateField.getText().trim());

//int yearsLoanManual = 20;
int yearsLoanManual = Integer.parseInt(yearsTermField.getText().trim());
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 12035148
Dear Rick,

I am glad to help. Can you tell me more about your problem?

Thanks.
0
 

Author Comment

by:RICKPOWELL1955
ID: 12035505
You are the man.
It seems to work great now.

I tried below on my own an got exception errors.
Seems it needed the trim() on the end

//                            double ratePercentManual =  Double.parseDouble(interestRateField.getText());

Thanks for your help again.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12035516
8-)
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now