Link to home
Start Free TrialLog in
Avatar of RICKPOWELL1955
RICKPOWELL1955

asked on

How do I get the variable arraynum to work in my program

I can not get this program to work correctly. Please show me what I am doing wrong.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
import java.text.*;
import javax.swing.text.*;

public class MortgageCalc extends JApplet   // Create Mortgage class with extended JApplets
     {
         JLabel label_1;                     //  Add label for Loan Amount
         JLabel label_2;                     //  Add label for Interest Rate
         JLabel label_3;                     //  Add label for Term (years loan)
         JTextField textfield_1;          //  Add field for Loan Amount
         JTextField textfield_2;          //  Add field for Interest Rate
         JTextField textfield_3;          //  Add field for Term (years loan)
         JButton calculate;               //  Create calculate button
         JLabel label_4;                    //  Add label space for Monthly Payment Amount
         JButton Start_Over;             //  Create Start Over button
         JLabel label_5;                    //  Add label for Monthly Payment Amount field data
         JButton Quit_Program;        //  Create Quit button to exit program
         JLabel label_6;                    //  Add label for Quit button
         JLabel label_7;                    //  Error message label header
         JLabel label_8;                    //  Error code message
         JLabel label_9;                    //  Error message help
         JLabel label_10;                  //  Loan Amount error message
         JLabel label_11;                  //  Interest Rate error message
         JLabel label_12;                  //  Term (years) error message
         JTextArea textArea;            //  Text Area for streaming data report
        JLabel label_13;                   //  Create Pre selected rates/terms label

        static String rate1String = "7 years  - 5.25%";
        static String rate2String = "15 years - 5.50%";
        static String rate3String = "30 years - 5.75%";

         private final static String newline = "\n";
         public static void main(String args[])
             {
                  JFrame f = new JFrame("Mortgage Loan Calculator");        //  Create JFrame
                  MortgageCalc calc = new MortgageCalc();                        //  Start MortgageCalc method
                  f.getContentPane().add(calc);                                          //  Add MortgageCalc method to JFrame Panel
                  calc.init();
                  f.pack();
                  f.setVisible(true);
             }   // End Main block
         public void init()
             {
                       MortgageCalcLayout customLayout = new MortgageCalcLayout();
                  Container con = getContentPane();
                  con.setFont(new Font("Helvetica", Font.BOLD, 12));
                  con.setLayout(customLayout);
                  label_1 = new JLabel("Loan Amount");                      //  Create label called Loan Amount
                  con.add(label_1);                                                    //  Add label to Container
                  label_1.setForeground(Color.yellow);                        //  Change Foreground color yellow

                  label_2 = new JLabel("Interest Rate");                       //  Create Label called Interest Rate
                  con.add(label_2);                                                     //  Add label to Container
                  label_2.setForeground(Color.yellow);                         //  Change Foreground color yellow

                  label_3 = new JLabel("Term");                                  //  Create label called Term
                  con.add(label_3);                                                     //  Add label to Container
                  label_3.setForeground(Color.yellow);                         //  Change Foreground color yellow

                  textfield_1 = new JTextField("");                                //  Initialize display for Loan Amount set to null
                  con.add(textfield_1);                                                 //  Add TextField to Container
                  textfield_1.setBackground(Color.yellow);                    //  Change Background color yellow

                  textfield_2 = new JTextField("");                                 //  Initialize display for Interest Rate set to null
                  con.add(textfield_2);                                                 //  Add TextField to Container
                  textfield_2.setBackground(Color.gray);                    //  Change Background color yellow
                  textfield_2.setEditable(false);

                  textfield_3 = new JTextField("");                                 //  Initialize display for Terms (years loan) set to null
                  con.add(textfield_3);                                                 //  Add TextField to Container
                  textfield_3.setBackground(Color.gray);                    //  Change Background color yellow
                  textfield_3.setEditable(false);

                 JButton calculate = new JButton("Calculate");              //  Create button called Calculate
                  con.add(calculate);                                                   //  Add Button to Container
                  calculate.setBackground(Color.red);                           //  Change Background color red
                  calculate.setForeground(Color.white);                         //  Change Foreground color white

                  label_4 = new JLabel("Payment");                              //  Create label called Payment
                  con.add(label_4);                                                      //  Add label to Container
                  label_4.setForeground(Color.yellow);                          //  Change Foreground color yellow

                  label_5 = new JLabel("$ ____________");                   //  Initialize display underline blank in monthly payment display
                  con.add(label_5);                                                      //  Add TextField to Container
                  label_5.setForeground(Color.yellow);                          //  Change Foreground color yellow

                 JButton Start_Over = new JButton("Start Over");           //  Create Button called Start_Over
                 con.add(Start_Over);                                                  //  Add Button to Container
                 Start_Over.setBackground(Color.yellow);                     //  Change Background color yellow

                 JButton Quit_Program = new JButton("Quit");               //  Create Button called Quit
                 con.add(Quit_Program);                                              //  Add Button to Container
                 Quit_Program.setForeground(Color.white);                    //  Change Foreground color white
                 Quit_Program.setBackground(Color.red);                      //  Change Background color red

                 label_7 = new JLabel("");                                             //  Create label for text header error condition
                 con.add(label_7);                                                        //  Add label to Container
                 label_7.setForeground(Color.white);                              //  Change Foreground color white
                 label_7.setVisible(true);                                               //  Set Error labell visible

                 label_8 = new JLabel("");                                             //  Create label  for actual error code
                 con.add(label_8);                                                        //  Add label to Container
                 label_8.setForeground(Color.white);                              //  Change Foreground color white
                 label_8.setVisible(true);                                               //  Set Error text visible

                 label_9 = new JLabel("");                                             //  Create label  for error message help
                 con.add(label_9);                                                        //  Add Error message help
                 label_9.setForeground(Color.white);                              //  Change Foreground color white
                 label_9.setVisible(true);                                               //  Set Error help  visible

                 label_10 = new JLabel("Input Error: Loan Amount must be 10000 - 200000");     //   Create label  for Loan Amount error message help
                 con.add(label_10);                                                       //  Add Loan Amount error message help
                 label_10.setVisible(false);                                             //  Set Loan Amount error help  visible
                 label_10.setForeground(Color.white);                             //  Change Foreground color white

                 label_11 = new JLabel("Input Error: Interest Rate must be  1 - 25");    //   Create label  for Interest Ratet error message help
                 con.add(label_11);                                                        //  Add Interest Rate error message help
                 label_11.setForeground(Color.white);                              //  Change Foreground color white
                 label_11.setVisible(false);                                              //  Set Interest Ratet error help  visible

                 label_12 = new JLabel("Input Error: Term Loan must be 7 - 30");         //   Create label  for Term (years) error message help
                 con.add(label_12);                                                         //  Add Term (years) error message help
                 label_12.setForeground(Color.white);                              //  Change Foreground color white
                 label_12.setVisible(false);                                              //  Set Term (years) error help  visible

                 label_13 = new JLabel("Pre selected Rates / Terms");      //  Create label for pre selected Rates / Terms
                 con.add(label_13);                                                         //  Add label to container
                 label_13.setForeground(Color.yellow);                             //  Set Foreground color to yellow

                 textArea = new JTextArea(5, 30);                                    //  Define text area for  principal, interest, balances
                 textArea.setText("");                                                       //  Print heading in textAre panel
                 textArea.setEditable(false);                                             //  set to false so user can't change data
                 con.add(textArea);                                                         //  Add textArea to panel

                 JRadioButton rate1Button = new JRadioButton(rate1String);
                 JRadioButton rate2Button = new JRadioButton(rate2String);
                 JRadioButton rate3Button = new JRadioButton(rate3String);

                 rate1Button.setMnemonic(KeyEvent.VK_7);
                 rate2Button.setMnemonic(KeyEvent.VK_1);
                 rate3Button.setMnemonic(KeyEvent.VK_3);

                 rate1Button.setActionCommand(rate1String);
                 rate2Button.setActionCommand(rate2String);
                 rate3Button.setActionCommand(rate3String);
                 rate1Button.setSelected(true);

                 ButtonGroup groupRate = new ButtonGroup();        //  Group the radio buttons.
                 groupRate.add(rate1Button);
                 groupRate.add(rate2Button);
                 groupRate.add(rate3Button);

                 rate1Button.setBackground(Color.green);
                 rate2Button.setBackground(Color.green);
                 rate3Button.setBackground(Color.green);

                 con.add(rate1Button);
                 con.add(rate2Button);
                 con.add(rate3Button);

                           rate1Button.addItemListener(new SelectItemListener());
                           rate2Button.addItemListener(new SelectItemListener());
                           rate3Button.addItemListener(new SelectItemListener());

                 //  Create scroll bars for textAre
                 textArea.setFont(new Font("Fixedsys", Font.PLAIN,12));
                 JScrollPane scrollPane = new JScrollPane(textArea,  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
                 con.add(scrollPane);                                          //  Add scrollbars to panel

                 setSize(getPreferredSize());

                 calculate.addActionListener(new ActionListener()
                      {
                           public void actionPerformed(ActionEvent h)
                               {
                                     double roundPayment = 0.0;                                   //   Initialize variables to 0
                                     DecimalFormat numberFormat = new DecimalFormat("$#,##0.00");    // Text format for outputs
                                          String displayPayment = "";                                    //   Display formatted payment
                                          boolean tripFlag = false;                                           //   Flag for error condition
                                          label_5.setText("$ ____________");
                                     textArea.setText("Payment            Month              Start Balance           Interest             Principal           End Balance "+newline);
                                     try
                                         {
                                              label_7.setVisible(false);                        //  Toggle error label header off
                                              label_8.setVisible(false);                        //  Toggle error message code off
                                              label_9.setVisible(false);                        //  Toggle error message help off
                                              label_10.setVisible(false);                      //  Toggle Loan Amount error message off
                                              label_11.setVisible(false);                      //  Toggle Interest Rate error message off
                                              label_12.setVisible(false);                      //  Toggle Term (years) error message off

                                                        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
                                              double principal =  Double.parseDouble(textfield_1.getText());            //  Principal to finance
                                                  if ( principal < 10000.00 || principal > 200000.00)
                                                      {
                                                                                                                                                                                                                                                       textfield_1.setText("0");                     //  Reset Loan Amount Field to 0
                                                         label_10.setVisible(true);                  //  Toggle Loan Amount error message on
                                                         label_5.setText("$ ____________");   //  Initialize Display underline blank in monthly payment display
                                                         tripFlag=true;
                                                                                                                                                                                                                                                }
                                              int arraynum = 2;                                                                                                                                                      //   array number used different choices of years and rate
                                                   double ratePercent[] = { 5.35f, 5.50f, 5.75f };                                                  //   rate of loan
                                                   double rate[] =             {       ratePercent[0]/100.00,                         ratePercent[1]/100.00,       ratePercent[2]/100.00       };      // rate in decimal format percentage
                                              int yearsLoan[] =   {  7,  15, 30 };                                                                         //   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] };      // number of payments for loan
                                                   double effectiveAnnualRate[] =      { rate[0] / paymentsPerYear,       rate[1] / paymentsPerYear, rate[2] / 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])))      }; //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]);

                                              if (tripFlag==false)
                                                   {
                                                        label_5.setText(formatPayment);                                  //  Output Monthly Payment to screen
                                                                                                                                                                                               }

                                                        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
                                                             textArea.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 try block
                                    catch (NumberFormatException e)
                                        {
                                             System.out.println("Number format error: " + e.getMessage());  // Debugging purposes to show output in DOS
                                             label_7.setVisible(true);                                        //  Toggle error label header on
                                             label_7.setText("Message Error:");                      //  Set error code title
                                             label_8.setVisible(true);                                        //  Toggle error message code on
                                             label_8.setText(e.getMessage());                       //  Set actual error code to label
                                             label_9.setVisible(true);                                       //  Toggle error message help on
                                             label_9.setText("Consult user manual for proper field values.");
                                             label_5.setText("$ ____________");                  //  Initialize Display underline blank in monthly payment display
                                        }  //  End catch block
                                                             }  //  End actionPerformed block
                       });  //  End calculate block


// Moved here - still does nto work
        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("7 years  - 5.25%"))
                                               {
                                         System.out.println("7 year loan at 5.25% selected");
                                             arraynum = 0;
//                                                                                                                                                                                textfield_2 = new JTextField("5.25");
//                                                                                                                                                                           textfield_3 = new JTextField("7");
                                     }
                                 else if (sel.getText().equals("15 years - 5.50%"))
                                          {
                                          System.out.println("15 year loan at 5.50% selected");
                                                   arraynum = 1;
//                                                                                                                                                                                            textfield_2 = new JTextField("5.50");
//                                                                                                                                                                                            textfield_3 = new JTextField("15");
                                          }
                                 else if (sel.getText().equals("30 years - 5.75%"))
                                           {
                                           System.out.println("30 year loan at 5.75% selected");
                                             arraynum = 2;
//                                                                                                                                                                                            textfield_2 = new JTextField("5.75");
//                                                                                                                                                                                            textfield_3 = new JTextField("30");
                                          }
                              }
                       }
              }


                  Start_Over.addActionListener(new ActionListener()
                      {
                           public void actionPerformed(ActionEvent h)
                                {
                                     textfield_1.setText("");                               //  Initialize Display to null
                                     textfield_2.setText("");                               //  Initialize Display to null
                                     textfield_3.setText("");                               //  Initialize Display to null
                                     label_5.setText("$ ____________");          //  Initialize Display underline blank in monthly payment display
                                     label_7.setVisible(false);                             //  Toggle error label header off
                                     label_8.setVisible(false);                             //  Toggle error message code off
                                     label_9.setVisible(false);                             //  Toggle error message help off
                                     label_10.setVisible(false);                           //  Toggle Loan Amount error message off
                                     label_11.setVisible(false);                           //  Toggle Interest Rate error message off
                                     label_12.setVisible(false);                           //  Toggle Term (years) error message off
                                     textArea.setText("");
                                }  // End actionPerformed block
                      });  //  End Start_Over listener

                  Quit_Program.addActionListener(new ActionListener()
                      {
                                               public void actionPerformed(ActionEvent h)
                                                   {
                                                                                                                                                                                                          System.exit(0);        // Exit code goes here
                                                    }  //  End Quit_Program block
                      });    //  End Quit_Program  Action Listener

              }  //  End void init block

          public static String formatColumn(double floatNumber)                  // Column format method
                         {
                             DecimalFormat numberFormat = new DecimalFormat("$#,##0.00");
                        String stringOfNum = numberFormat.format(floatNumber);
                        int numLen = stringOfNum.length();
                             if (numLen < 13) stringOfNum = "            ".substring(numLen) + stringOfNum;
                             return (stringOfNum);
                    }

               public static String formatMonthDate(int payMonth)                        // Month format Method
                         {
                                  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);
                    }
 } //   End MortgageCalc block
class MortgageCalcLayout implements LayoutManager
    {
         public MortgageCalcLayout()  {    }
         public void addLayoutComponent(String name, Component comp)    {    }
         public void removeLayoutComponent(Component comp)    {    }

         public Dimension preferredLayoutSize(Container parent)          //  Setup initial container size
              {
                   Dimension dim = new Dimension(0, 0);
                   Insets insets = parent.getInsets();
                   dim.width = 750 + insets.left + insets.right;
                   dim.height = 550 + insets.top + insets.bottom;
                   return dim;
               }    //  End preferredLayoutSize block

          public Dimension minimumLayoutSize(Container parent)         //  Create minimum applet container size
               {
                   Dimension dim = new Dimension(0, 0);
                   return dim;
               }  //  End minmumLayout Size block

          public void layoutContainer(Container parent)                      //  Create Screen Layout
               {
                     Insets insets = parent.getInsets();
                     Component c;
                     //  Parameters for setBounds(int x,  int y,  int width,  int height)
                     parent.setBackground(Color.blue);
                     c = parent.getComponent(0);
                     if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+8,96,24);}            //  Loan Amount label Text
                     c = parent.getComponent(1);
                     if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+40,96,24);}          //  Interest Rate label Text
                     c = parent.getComponent(2);
                     if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+72,96,24);}          //  Term (Years Loan) label Text
                     c = parent.getComponent(3);
                     if (c.isVisible()) {c.setBounds(insets.left+112,insets.top+8,112,24);}       //  Loan Amount Container Box
                     c = parent.getComponent(4);
                     if (c.isVisible()) {c.setBounds(insets.left+112,insets.top+40,112,24);}      //  Interest Rate Container Box
                     c = parent.getComponent(5);
                     if (c.isVisible()) {c.setBounds(insets.left+112,insets.top+72,112,24);}      //  Term (Years loan) Container Box
                     c = parent.getComponent(6);
                     if (c.isVisible()) {c.setBounds(insets.left+112,insets.top+104,112,24);}    //  Calculate container
                     c = parent.getComponent(7);
                     if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+136,96,24);}          //  Payment label Text
                     c = parent.getComponent(8);
                     if (c.isVisible()) {c.setBounds(insets.left+112,insets.top+136,112,24);}    //   Payment Monthly Amount Display
                     c = parent.getComponent(9);
                     if (c.isVisible()) {c.setBounds(insets.left+112,insets.top+175,112,24);}     //   Restart Button container
                     c = parent.getComponent(10);
                     if (c.isVisible()) {c.setBounds(insets.left+250,insets.top+175,112,24);}     //  Quit Button container
                     c = parent.getComponent(11);
                     if (c.isVisible()) {c.setBounds(insets.left+250,insets.top+136,96,24);}       //  Error message label header
                     c = parent.getComponent(12);
                     if (c.isVisible()) {c.setBounds(insets.left+350,insets.top+136,200,24);}     //  Error message code
                     c = parent.getComponent(13);
                     if (c.isVisible()) {c.setBounds(insets.left+250,insets.top+104,250,24);}     //  Error message help
                     c = parent.getComponent(14);
                     if (c.isVisible()) {c.setBounds(insets.left+250,insets.top+8,300,24);}        //  Loan Amount error message
                     c = parent.getComponent(15);
                     if (c.isVisible()) {c.setBounds(insets.left+250,insets.top+40,300,24);}      //  Interest Rate error message
                     c = parent.getComponent(16);
                     if (c.isVisible()) {c.setBounds(insets.left+250,insets.top+72,300,24);}      // Term (years) error message

                     c = parent.getComponent(17);
                     if (c.isVisible()) {c.setBounds(insets.left+550,insets.top+8,200,24);}         //  Preselected Rates / Terms label title
                     c = parent.getComponent(18);
                     if (c.isVisible()) {c.setBounds(insets.left+550,insets.top+40,125,28);}      //  Preselected Rates / Terms rate1Button
                     c = parent.getComponent(19);
                     if (c.isVisible()) {c.setBounds(insets.left+550,insets.top+72,125,28);}      //  Preselected Rates / Terms rate2Button
                     c = parent.getComponent(20);
                     if (c.isVisible()) {c.setBounds(insets.left+550,insets.top+104,125,28);}    //  Preselected Rates / Terms rate3Button

                     c = parent.getComponent(21);
                     if (c.isVisible()) {c.setBounds(insets.left+25,insets.top+275,650,250);}      //  Text Area for Payment Report

               }  //  End layoutContainer block

    }  //  End MortgageCalct block
Avatar of girionis
girionis
Flag of Greece image

What exactly is the problem?
Avatar of RICKPOWELL1955
RICKPOWELL1955

ASKER

I could not get the program to pass the variable "arraynum" once the radioButton was selected because it was in a seperate class.
ASKER CERTIFIED SOLUTION
Avatar of RuadRauFlessa
RuadRauFlessa

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
also make it an inner class.

by defining arraynum in your outer class you should be able to address it from the inner class. You could also try static variables. Make sure though when you make use of stattic variables that you restrict the access to that specific variable.