Mortgage Calculator in Java

Can anyone help me figure out how to change my mortgage calculator to do the following?
Modify the mortgage program to display the mortgage payment amount. Then, list the loan balance and interest paid for each payment over the term of the loan. The list would scroll off the screen, but use loops to display a partial list, hesitate, and then display more of the list. Do not use a graphical user interface. Insert comments in the program to document the program. Here is the code I have currently.
import java.io.*;
import java.text.DecimalFormat;
public class MortgageRateWeek3Test
     public static void main(String[] args) throws IOException
          //Declaring and Constructing Variables
          int iTerm;
          double dInterest = 5.75;
          double dPayment, dRate, dAmount = 200000, dMonthlyInterest,dMonthlyPrincipal, dMonthlyBalance;
          DecimalFormat twoDigits = new DecimalFormat("$#,000.00");
                    //Calculations Retrieved from http://www.1728.com/loanform.htm on 9/14/05
                    dRate = dInterest / 1200;
                    iTerm = 360;
                    dPayment = (dAmount * dRate) / (1 - Math.pow(1 / (1 + dRate), iTerm));
                    dMonthlyInterest = (dAmount / 12) * (dInterest / 100);
                    dMonthlyPrincipal = (dPayment - dMonthlyInterest);
                    dMonthlyBalance = (dAmount - dMonthlyPrincipal);
                              // Output dPayment
                              System.out.println();
                              System.out.println("\tYour Monthly Payment is: " + twoDigits.format (dPayment));
                              System.out.println();
     public class monthlyInterest
          //Declaring Variables for monthlyInterest
          double dMonthlyInterest = 0.0;
          double dAmount = 0.0;
          double dInterest = 0.0;
               //Calculations for monthlyInterest
               dMonthlyInterest = (dAmount / 12) * (dInterest / 100);
          return dMonthlyInterest;
     public static double monthlyPrincipal()
          //Declaring Variables for monthlyPrincipal
          double dMonthlyPrincipal = 0.0;
          double dPayment = 0.0;
          double dMonthlyInterest = 0.0;
               //Calculations for monthlyPrincipal
               dMonthlyPrincipal = (dPayment - dMonthlyInterest);
          return dMonthlyPrincipal;
     public static double monthlyBalance()
          //Declaring Variables for monthlyBalance
          double dMonthlyBalance = 0.0;
          double dAmount = 0.0;
          double dMonthlyPrincipal = 0.0;
               //Calculations for monthlyBalance
               dMonthlyBalance = (dAmount - dMonthlyPrincipal);
          return dMonthlyBalance;
}

There are imports that aren't available to us, so no. nobody probaly can. Of course maybe someon could be bothered going through all of your code, and may spot some mistake. But I doubt they will since you didn't bother to use [c[b]ode] tags.

Similar Messages

  • How is the length of a string calculated in Java?  and JavaScript?

    Hi all,
    Do any of you know how the length of a string is being calculated in Java and JavaScript? For example, a regular char is just counted as 1 char, but sometimes other chars such as CR, LF, and CR LF are counted as two. I know there are differences in the way Java and JavaScript calculate the length of a string, but I can't find any sort of "rules" on those anywhere online.
    Thanks,
    Yim

    What's Unicode 4 got to do with it? 1 characteris 1
    character is 1 character.
    strings now contain (and Java chars also) is
    UTF-16 code units rather than Unicode characters
    or
    code points. Unicode characters outside the BMPare
    encoded in Java as two or more code units. So it would seem that in some cases, a single
    "character" on the screen, will require two charsto
    represent it.So... you're saying that String.length() doesn't
    account for that? That sux. I don't know. I'm just making infrerences (==WAGs) based on what DrClap said.
    I assume it would return the number of chars in the array, rather than the number of symbols (glyphs?) this translates into. But I might have it bass ackwards.

  • Graphical chart in a mortgage calculator

    I need to add a graphical amortization chart to my mortgage calculator program.
    I don't have a clue how to start. Does anyone know of any reading material
    I could get my hands on that would help me out?
    An example to work with would be nice, but I will settle for
    some extra reading material to study.
    thank you.

    I don't think I am allowed to use third party stuff
    what I need to do is devise a chart that will show the interest paid as well as the principal payment as two lines on an a graph
    when you change the interest rate and term of the loan
    and recalculate. the graph shows the new interest and principal

  • Java Mortgage Calculator

    Im having trouble making my GUI look the way I want it. Obviously I dont know enough about Gridlayout And I think I need to use GridBagLayout instead. I need the amortization schedule to print all the way out and everything to line up. If anyone has some suggestions I would love to hear it, and yes, this is my homework. see the code below:
    Main java file: implements MyFrame4 java file
    import java.awt.*; //imports awt
    public class MortgageCalculator4 {   // main MortgageCalculator class constuctor
    public static void main(String args[]) {  //implements MyFrame4
    Frame f = new MyFrame4();
    } //end of MortgageCalculator4 class
    Adapter java file: implements WindowAdapter
    import java.awt.*; //imports awt
    import java.awt.event.*;
    class MyAdapter extends WindowAdapter {   //creates window adapter
    Frame myFrame;
    MyAdapter(Frame f) {
    super();
    myFrame = f;
    public void windowClosing(WindowEvent e) {
    myFrame.dispose();
    } //end of MyAdapter class
    Frame java file: main body of program implemented by MortgageCalculator file
    import java.awt.*; //imports awt's
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    class MyFrame4 extends Frame implements TextListener, ActionListener {    //class constructs the frame and layout
    Button loanButton1 = new Button("Loan 1"), //creates and labels buttons
    loanButton2 = new Button("Loan 2"),
    loanButton3 = new Button("Loan 3"),
    clearButton = new Button("clear/New");
    TextField principalField = new TextField("0.00", 15), //sets TextField properties
    rateField = new TextField("0.00", 3), //adds field lenghts and initial properties
    yearsField = new TextField("0", 3),
    paymentField = new TextField("0.00", 15),
    intpaymentTextArea = new TextField("0.00", 40);
    double principal, rate, ratePercent; //assigns variables
    int years, n;
    final int paymentsPerYear = 12;
    final int timesPerYearCalculated = 12;
    double effectiveAnnualRate;
    double payment;      
    public MyFrame4() { //beginnig of frame constructor
    setTitle("Mortgage Payment Calculator");
    setLayout(new GridLayout(14, 2));
    Label title1Label = new Label("Enter loan amount then select a loan option");
    Label title2Label = new Label("or enter an interest rate and years");
    Label principalLabel = new Label("Loan Amount $"), // constructs labels
    rateLabel = new Label("Rate (%)"),
    yearsLabel = new Label("Years"),
    loan1Label = new Label("7 years at 5.35%"), //asigns labels
    loan2Label = new Label("15 years at 5.5%"),
    loan3Label = new Label("30 years at 5.75%%"),
    paymentLabel = new Label("Payment $"),
    intpaymentLabel = new Label("Ammortization Schedule");
    Panel title1LabelPanel = new Panel (new FlowLayout(FlowLayout.RIGHT));
    Panel title2LabelPanel = new Panel (new FlowLayout(FlowLayout.RIGHT));
    Panel principalLabelPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)), // places label positions and button panels
    loan1LabelPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    loan2LabelPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    loan3LabelPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    rateLabelPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    yearsLabelPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    paymentLabelPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    intpaymentLabelPanel = new Panel(new FlowLayout(FlowLayout.CENTER));
    Panel principalFieldPanel = new Panel(new FlowLayout(FlowLayout.LEFT)),
    loan1ButtonPanel = new Panel(new FlowLayout(FlowLayout.LEFT)),
    loan2ButtonPanel = new Panel(new FlowLayout(FlowLayout.LEFT)),
    loan3ButtonPanel = new Panel(new FlowLayout(FlowLayout.LEFT)),
    rateFieldPanel = new Panel(new FlowLayout(FlowLayout.LEFT)),
    yearsFieldPanel = new Panel(new FlowLayout(FlowLayout.LEFT)),
    paymentFieldPanel = new Panel(new FlowLayout(FlowLayout.LEFT)),
    clearButtonPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    blankPanel = new Panel(new FlowLayout(FlowLayout.RIGHT)),
    intpaymentTextAreaPanel = new Panel(new FlowLayout(FlowLayout.RIGHT));
    title1LabelPanel.add(title1Label);
    title1LabelPanel.add(title2Label);
    principalLabelPanel.add(principalLabel); //adds labels buttons and fields
    principalFieldPanel.add(principalField);
    loan1LabelPanel.add(loan1Label);
    loan1ButtonPanel.add(loanButton1);
    loan2LabelPanel.add(loan2Label);
    loan2ButtonPanel.add(loanButton2);
    loan3LabelPanel.add(loan3Label);
    loan3ButtonPanel.add(loanButton3);
    clearButtonPanel.add(clearButton);
    rateLabelPanel.add(rateLabel);
    rateFieldPanel.add(rateField);
    rateField.setEditable(true);
    yearsLabelPanel.add(yearsLabel);
    yearsFieldPanel.add(yearsField);
    yearsField.setEditable(true);
    paymentLabelPanel.add(paymentLabel);
    paymentFieldPanel.add(paymentField);
    paymentField.setEditable(false);
    intpaymentLabelPanel.add(intpaymentLabel);
    intpaymentTextAreaPanel.add(intpaymentTextArea);
    intpaymentTextArea.setEditable(false);
    add(title1LabelPanel);
    add(title2LabelPanel);
    add(principalLabelPanel);
    add(principalFieldPanel);
    add(loan1LabelPanel);
    add(loan1ButtonPanel);
    add(loan2LabelPanel);
    add(loan2ButtonPanel);
    add(loan3LabelPanel);
    add(loan3ButtonPanel);
    add(rateLabelPanel);
    add(rateFieldPanel);
    add(yearsLabelPanel);
    add(yearsFieldPanel);
    add(paymentLabelPanel);
    add(paymentFieldPanel);
    add(clearButtonPanel);
    add(intpaymentLabelPanel);
    add(blankPanel);
    add(intpaymentTextAreaPanel);
    loanButton1.addActionListener(this); //assigns ActionListener to buttons
    loanButton2.addActionListener(this);
    loanButton3.addActionListener(this);
    clearButton.addActionListener(this);
    principalField.addTextListener(this); //adds TextListener to fields
    rateField.addTextListener(this);
    yearsField.addTextListener(this);
    addWindowListener(new MyAdapter(this));
    pack(); //resizes window to fit components
    setVisible(true);
    DecimalFormat currency = new DecimalFormat("####0.00"); //sets currency format
    public void actionPerformed(ActionEvent e){ //checks for buttons clicked and sets variables to fields
         //wanted to get data from array but couldnt make it work
              if(e.getSource() == loanButton1){
                   rateField.setText("5.85");
                   yearsField.setText("7");
         if(e.getSource() == loanButton2){
                   rateField.setText("5.5");
              yearsField.setText("20");           
              if(e.getSource() == loanButton3){
                   rateField.setText("5.75");
              yearsField.setText("30");     
              if(e.getSource() == clearButton){
                   rateField.setText("0.00");
              yearsField.setText("0");
              principalField.setText("0.00");           
    public void textValueChanged(TextEvent e) {  //checks field variables and sends to calculations
    Object source = e.getSource();
    if (source == principalField
    || source == rateField
    || source == yearsField) {
    try {
    principal = Double.parseDouble(principalField.getText()); //perform calculations for payment
    ratePercent = Double.parseDouble(rateField.getText());
    rate = ratePercent / 100.0;
    years = Integer.parseInt(yearsField.getText());
    n = paymentsPerYear * years;
    effectiveAnnualRate = rate / paymentsPerYear;
    payment =
    principal
    * (effectiveAnnualRate
    / (1 - Math.pow(1 + effectiveAnnualRate, -n)));
    DecimalFormat payForm = new DecimalFormat("####.##"); //performs calculations for Ammortization text area
    int num_Months = years*12;     
    double i = ratePercent/1200;
    payment = principal*((i*(Math.pow((1+i),num_Months)))/((Math.pow((1+i),num_Months))-1));               
    int num_Payments = num_Months-1;
    int month_counter = 0;
    double intPaid = 0;
    double balance = principal;
    intpaymentTextArea.setText("");
    while (month_counter <= num_Months){
    intPaid = balance * i;
    balance = balance - (payment - intPaid);
    intpaymentTextArea.setText(("Month ")+month_counter+( " - Payment: $")
    payForm.format(payment)" Balance: "
    payForm.format(balance)(" Interest Paid: $")
    payForm.format(intPaid)"\n");
    month_counter++;
    paymentField.setText(currency.format(payment)); //display payment
    } catch (NumberFormatException ex) {  //catch exceptions
    } //end of MyFrame4 Class

    Another suggestion is post only the necessary code that exemplifies the unexpected behavior, and don't forget to use code tags when you're posting code. Look for CODE button when writing the post! This way your code will be well formatted and more readable. It also increases the chance of someone reading it and help you.

  • Wrong values from calculated field (Java API)

    Hi All,
    Help me please solve the problem.
    We have a table with calculated text field in MDM repositor. For some records the value of this field in MDM Data Manager differs from the value returned when we read record by MDM Java API.
    Parameters of system:
    MDM ver.: 7.1 SP10
    DBMS: Oracle
    OS: Linux
    The issue solved. I've found error in program code :-)
    I apologize for the worry.

    Assuming you want every field, the equivalent of "SELECT *" in SQL, you can use the RepositorySchema object to get a TableSchema, and with that get all FieldIds for the table.
    If your RepositorySchema variable is rs it would be something along the lines of:
    TableSchema mainTableSchema = rs.getTableSchema(mainTableId);
    ResultDefinition rd = new ResultDefinition(mainTableId);
    rd.setSelectFields(mainTableSchema.getFieldIds());
    Hope this helps,
    Greg

  • How do I add a mortgage calculator or any calculator

    how do I add to a realtors website a mortgage calculator

    Hi,
    I was wondering if there is a way of adding a different type of calculator into Muse.  I am opening a printing business and would like to have a calculator for clients to be able to calculate the price of their prints based on the dimensions they choose.  The client would enter the height and width of his/her print and get the price automatically calculated for them.  I also would like for the calculator to give the client the minimum number of pixels to produce such print.  I can create such calculator on Excel.  Would it be possible to embed it into Muse somehow?  Many thanks for your help!

  • Eigen Calculations in Java

    Hi,
    Iam currently writing java code for PCA statistical calculation (for 500*500 matrix) in Java. I would have to match the results with SAS calculation of PCA using PRINCOMP PROC.
    Could somebody help on java resources available for statistical calculations. I tried some, they follow algorithms like QR/Householder, Jacobi. But the results are not matching SAS. I am currently off by more decimal places for Eigen calculations when compared to SAS.
    Appreciate you direction on this.
    Thanks,
    Shyam

    ShyamKrishnan wrote:
    Sorry being precised in prevous post. Please see my answers below:
    Is this what you're doing? -Yes
    http://www.pfc.forestry.ca/profiles/wulder/mvstats/pca_fa_e.html
    You say your matricies are "huge", but you don't give any other information about whether they're symmetric, sparse, banded, etc.
    They matrix is of order 800*7000. Not square? Oh, my.
    They dont follow any specific category like symmetric or sparse.. Not symmetric - so you have complex eigenvalues.
    You don't say if you need just eigenvalues or eigenvectors, too. - Need both Eigen vectors and valuesSAS gets these for you?
    You don't say if you need all the eigenvalues or just the first few. - Need allWhat algorithm is SAS using?
    I'm confused about the precision problem. Isn't that determined by the floating point representation? Its not due to floating point.. I mean there is something more than that.Like what? There might be accumulated numerical error in the algorithm, but if that's the case don't use the word precision.
    Maybe you need a method with shifts. - May be you r rightPower method with shifts, but the one that I've seen is for symmetric matricies with real eigenvalues.
    Did you write the eigenvalue extraction yourself? - Mine was not as good as jama. Obviously.
    What algorithm did you choose? Was it appropriate for non-symmetric matricies?
    Or did you just use JAMA - Yes but it didnt match for huge dataWhat does "match" look like? Were some of the eigenvalues off? All of them? The eigenvectors? What were the absolute and relative errors? You're talking about hundreds of eigenvalues and their corresponding eigenvectors.
    The physics problems that I'm used to result in square, symmetric matricies and real eigenvectors. The eigenvectors span the space and form a basis. What happens with a non-square matrix? What's the basis in that case?
    If SAS has already given you the values, why is it necessary to do it again with Java? - Rqmt is to rewrite the SAS in JavaSo it's a school assignment.
    How are you checking correctness? What makes you so sure that SAS is 100% correct?
    Have you tried JAMA and your home-rolled code against some known problems to make sure that you understand what's going on? You're a fool if you submit your full case and use that to decide the fate of the code.
    %

  • Money calculation using Java

    Hi,
    I have problem with calculating the total amounts. I am not sure what's wrong with the below code snippet, could anyone help me please.
    If the value of authDoubleAmount in line 3 of code below is 34.8, by casting to long it returns 3479. I am loosing the precession of value 01 after the decimal point. How do I get 3480 instead of 3479.
    BigDecimal authBigDecimalAmount =authMoneyAmount.getRoundedValue(2, BigDecimal.ROUND_HALF_DOWN);
    double authDoubleAmount = authBigDecimalAmount.doubleValue();
    long authLongAmount = (long) (authDoubleAmount * 100);
    Thanks

    If you are working with money, you SHOULD NEVER use float or double, for they represent numbers in a non continuous way (there are numbers lacking, that they cannot hold) , you should work with them through the BigDecimal mehtods.
    May the code be with you.

  • Need Java Help on a Mortgage program

    I keep getting the following error.
    java:20: illegal start of expression
    public Scanner myScanner = new Scanner(System.in);
    /*Danielle Safonte*/
    /* Week 2 Mortgage Calculator*/
    import java.util.Scanner;
    import java.io.*;
    import java.text.*;
    public class Week2Assignment
    int principle = 200000;
    float interest = .0575;
    int term = 30;
    int months;
    float paymentdue;
    float calculation;
    public static void months()
    public Scanner myScanner = new Scanner(System.in);
    System.out.print("What month of the loan is this?" + months);
    if (months = term) {
    System.out.print("You have paid off your loan");
    else
         months = myScanner.next();
         float Jinterest = (interest / (months*100));
         calculation = principle * (Jinterest/(1-(1+Jinterest)^(-months))); /*Monthly payment*/
         float Minterest = principle * Jinterest; /*This months interest*/
         float Mprinciple = calculation - Minterest; /*This months principle*/
         float newBalance = principle - Mprinciple; /*This calculates the new principle*/
         if (newBalance = princple) {
              System.out.print("You have paid off your loan");
         else
              System.out.print("This months payment is: $", calculation); /*Displays the current months payment*/
              System.out.print("You have $", newBalance," left on your loan"); /*Displays the new principle balance*/
              System.out.print("This months principle is: $", Mprinciple ); /*Displays the new principle balance*/
    }

    It is in my post at 10:02, but here it is again:
    These are the errors that I am left with. I worked through the rest.
    .java:29: '.class' expected
    months = myScanner.next(int);
    ^
    .java:29: ')' expected
    months = myScanner.next(int);
    ^
    2 errors
    Tool completed with exit code 1
    import java.util.Scanner;
    import java.io.*;
    import java.text.*;
    public class Week2Assignment
    int principle = 200000;
    double  interest = .0575;
    int term = 30;
    int months;
    float paymentdue;
    float calculation;
    public void months()
    Scanner myScanner = new Scanner(System.in);
       System.out.print("What month of the loan is this?" + months);
    if (months == term) {
       System.out.print("You have paid off your loan");
    else
         months = myScanner.next(int);
         double Jinterest = (interest / (months*100));
         calculation = principle * (Jinterest/(1-(1+Jinterest)^(-months))); /*Monthly payment*/
         float Minterest = principle * Jinterest; /*This months interest*/
         float Mprinciple = calculation - Minterest; /*This months principle*/
         float newBalance = principle - Mprinciple; /*This calculates the new principle*/
         if (newBalance == princple) {
                 System.out.print("You have paid off your loan");
         else
                 System.out.print("This months payment is: $", calculation); /*Displays the current months payment*/
                 System.out.print("You have $", newBalance," left on your loan"); /*Displays the new principle balance*/
                 System.out.print("This months principle is: $", Mprinciple ); /*Displays the new principle balance*/
    }

  • Need Help with this code

    I am very new to java (just started today), and I am trying to do a mortgage calculator in java. I have a class file which I am using but when I try to compile it, I get the error message "Exception in thread "main" java.lang.NoClassDefFoundError: Mortgage Loan". I realize that this means I am missing a public static void somewhere (sounds like I know what I am talking about huh?) The problem is I don't know where to put it or even what to put in it. I got the code from another site and it seems to work fine there. Here is the code for the class file....any help anyone can offer will be greatly appreciated. thx
    import KJEgraph.*;
    import KJEgui.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.io.PrintStream;
    public class MortgageLoan extends CalculatorApplet
    public MortgageLoan()
    RC = new MortgageLoanCalculation();
    cmbPREPAY_TYPE = new KJEChoice();
    lbLOAN_AMOUNT = new Label("");
    lbINTEREST_PAID = new Label("");
    lbTOTAL_OF_PAYMENTS = new Label("");
    lbMONTHLY_PI = new Label("");
    lbMONTHLY_PITI = new Label("");
    lbPREPAY_INTEREST_SAVINGS = new Label("");
    public double getPayment()
    calculate();
    return RC.MONTHLY_PI;
    public void initCalculatorApplet()
    tfINTEREST_RATE = new Nbr("INTEREST_RATE", "Interest rate", 1.0D, 25D, 3, 4, this);
    tfTERM = new Nbr("TERM", "Term", 0.0D, 30D, 0, 5, this);
    tfLOAN_AMOUNT = new Nbr("LOAN_AMOUNT", "Mortgage amount", 100D, 100000000D, 0, 3, this);
    tfPREPAY_STARTS_WITH = new Nbr("PREPAY_STARTS_WITH", "Start with payment", 0.0D, 360D, 0, 5, this);
    tfPREPAY_AMOUNT = new Nbr("PREPAY_AMOUNT", "Amount", 0.0D, 1000000D, 0, 3, this);
    if(getParameter("PAYMENT_PI") == null)
    tfPAYMENT_PI = new Nbr(0.0D, getParameter("MSG_PAYMENT_PI", "Payment"), 0.0D, 10000D, 0, 3);
    else
    tfPAYMENT_PI = new Nbr("PAYMENT_PI", "Payment", 0.0D, 10000D, 0, 3, this);
    tfYEARLY_PROPERTY_TAXES = new Nbr("YEARLY_PROPERTY_TAXES", "Annual property taxes", 0.0D, 100000D, 0, 3, this);
    tfYEARLY_HOME_INSURANCE = new Nbr("YEARLY_HOME_INSURANCE", "Annual home insurance", 0.0D, 100000D, 0, 3, this);
    super.nStack = 1;
    super.bUseNorth = false;
    super.bUseSouth = true;
    super.bUseWest = true;
    super.bUseEast = false;
    RC.PREPAY_NONE = getParameter("MSG_PREPAY_NONE", RC.PREPAY_NONE);
    RC.PREPAY_MONTHLY = getParameter("MSG_PREPAY_MONTHLY", RC.PREPAY_MONTHLY);
    RC.PREPAY_YEARLY = getParameter("MSG_PREPAY_YEARLY", RC.PREPAY_YEARLY);
    RC.PREPAY_ONETIME = getParameter("MSG_PREPAY_ONETIME", RC.PREPAY_ONETIME);
    RC.MSG_YEAR_NUMBER = getParameter("MSG_YEAR_NUMBER", RC.MSG_YEAR_NUMBER);
    RC.MSG_PRINCIPAL = getParameter("MSG_PRINCIPAL", RC.MSG_PRINCIPAL);
    RC.MSG_INTEREST = getParameter("MSG_INTEREST", RC.MSG_INTEREST);
    RC.MSG_PAYMENT_NUMBER = getParameter("MSG_PAYMENT_NUMBER", RC.MSG_PAYMENT_NUMBER);
    RC.MSG_PRINCIPAL_BALANCE = getParameter("MSG_PRINCIPAL_BALANCE", RC.MSG_PRINCIPAL_BALANCE);
    RC.MSG_PREPAYMENTS = getParameter("MSG_PREPAYMENTS", RC.MSG_PREPAYMENTS);
    RC.MSG_NORMAL_PAYMENTS = getParameter("MSG_NORMAL_PAYMENTS", RC.MSG_NORMAL_PAYMENTS);
    RC.MSG_PREPAY_MESSAGE = getParameter("MSG_PREPAY_MESSAGE", RC.MSG_PREPAY_MESSAGE);
    RC.MSG_RETURN_AMOUNT = getParameter("MSG_RETURN_AMOUNT", RC.MSG_RETURN_AMOUNT);
    RC.MSG_RETURN_PAYMENT = getParameter("MSG_RETURN_PAYMENT", RC.MSG_RETURN_PAYMENT);
    RC.MSG_GRAPH_COL1 = getParameter("MSG_GRAPH_COL1", RC.MSG_GRAPH_COL1);
    RC.MSG_GRAPH_COL2 = getParameter("MSG_GRAPH_COL2", RC.MSG_GRAPH_COL2);
    cmbPREPAY_TYPE.addItem(RC.PREPAY_NONE);
    cmbPREPAY_TYPE.addItem(RC.PREPAY_MONTHLY);
    cmbPREPAY_TYPE.addItem(RC.PREPAY_YEARLY);
    cmbPREPAY_TYPE.addItem(RC.PREPAY_ONETIME);
    cmbPREPAY_TYPE.select(getParameter("PREPAY_TYPE", RC.PREPAY_NONE));
    CheckboxGroup checkboxgroup = new CheckboxGroup();
    cbPRINCIPAL = new Checkbox(getParameter("MSG_CHKBOX_PRINCIPAL_BAL", "Principal balances"), checkboxgroup, true);
    cbAMTS_PAID = new Checkbox(getParameter("MSG_CHKBOX_TOTAL_PAYMENTS", "Total payments"), checkboxgroup, false);
    CheckboxGroup checkboxgroup1 = new CheckboxGroup();
    cbYEAR = new Checkbox(getParameter("MSG_CHKBOX_BY_YEAR", "Report amortization schedule by year"), checkboxgroup1, true);
    cbMONTH = new Checkbox(getParameter("MSG_CHKBOX_BY_MONTH", "Report amortization schedule by Month"), checkboxgroup1, false);
    cbYEAR.setBackground(getBackground());
    cbMONTH.setBackground(getBackground());
    setCalculation(RC);
    cmbTERM = getMortgageTermChoice(getParameter("TERM", 30));
    public void initPanels()
    DataPanel datapanel = new DataPanel();
    DataPanel datapanel1 = new DataPanel();
    DataPanel datapanel2 = new DataPanel();
    int i = 1;
    datapanel.setBackground(getColor(1));
    boolean flag = getParameter("SHOW_PITI", false);
    boolean flag1 = getParameter("SHOW_PREPAY", true);
    datapanel.addRow(new Label(" " + getParameter("MSG_LOAN_INFORMATION", "Loan Information") + super._COLON), getBoldFont(), i++);
    datapanel.addRow(tfLOAN_AMOUNT, getPlainFont(), i++);
    bAllTerms = getParameter("SHOW_ALLTERMS", false);
    if(bAllTerms)
    datapanel.addRow(tfTERM, getPlainFont(), i++);
    else
    datapanel.addRow(getParameter("MSG_TERM", "Term") + super._COLON, cmbTERM, getPlainFont(), i++);
    datapanel.addRow(tfINTEREST_RATE, getPlainFont(), i++);
    if(flag)
    datapanel.addRow(tfYEARLY_PROPERTY_TAXES, getPlainFont(), i++);
    datapanel.addRow(tfYEARLY_HOME_INSURANCE, getPlainFont(), i++);
    if(flag)
    datapanel.addRow(getParameter("MSG_MONTHLY_PAYMENT", "Monthly payment (PI)") + " " + super._COLON, lbMONTHLY_PI, getPlainFont(), i++);
    datapanel.addRow(getParameter("MSG_PITI", "Monthly payment (PITI)") + " " + super._COLON, lbMONTHLY_PITI, getPlainFont(), i++);
    } else
    datapanel.addRow(getParameter("MSG_MONTHLY_PAYMENT", "Monthly payment") + " " + super._COLON, lbMONTHLY_PI, getPlainFont(), i++);
    if(!flag || !flag1)
    datapanel.addRow(getParameter("MSG_TOTAL_PAYMENTS", "Total payments") + " " + super._COLON, lbTOTAL_OF_PAYMENTS, getPlainFont(), i++);
    datapanel.addRow(getParameter("MSG_TOTAL_INTEREST", "Total interest") + " " + super._COLON, lbINTEREST_PAID, getPlainFont(), i++);
    datapanel.addRow("", new Label(""), getTinyFont(), i++);
    if(flag1)
    datapanel.addRow(new Label(" " + getParameter("MSG_PREPAYMENTS", "Prepayments") + " " + super._COLON), getBoldFont(), i++);
    datapanel.addRow(getParameter("MSG_PREPAYMENT_TYPE", "Type") + " " + super._COLON, cmbPREPAY_TYPE, getPlainFont(), i++);
    datapanel.addRow(tfPREPAY_AMOUNT, getPlainFont(), i++);
    datapanel.addRow(tfPREPAY_STARTS_WITH, getPlainFont(), i++);
    datapanel.addRow(getParameter("MSG_PREPAYMENT_SAVINGS", "Savings") + " " + super._COLON, lbPREPAY_INTEREST_SAVINGS, getPlainFont(), i++);
    Panel panel = new Panel();
    panel.setBackground(getColor(1));
    panel.setLayout(new BorderLayout());
    panel.add("Center", datapanel);
    panel.add("East", new Label(""));
    cbPRINCIPAL.setBackground(getColor(2));
    cbAMTS_PAID.setBackground(getColor(2));
    datapanel2.setBackground(getColor(2));
    datapanel1.addRow("", cbYEAR, "", cbMONTH, getPlainFont(), 1);
    datapanel2.addRow("", cbPRINCIPAL, "", cbAMTS_PAID, getPlainFont(), 1);
    gGraph = new Graph(new GraphLine(), imageBackground());
    gGraph.FONT_TITLE = getGraphTitleFont();
    gGraph.FONT_BOLD = getBoldFont();
    gGraph.FONT_PLAIN = getPlainFont();
    gGraph.setBackground(getColor(2));
    gGraph.setForeground(getForeground());
    Panel panel1 = new Panel();
    panel1.setLayout(new BorderLayout());
    panel1.add("North", datapanel2);
    panel1.add("Center", gGraph);
    panel1.setBackground(getColor(2));
    addPanel(panel);
    addDataPanel(datapanel1);
    addPanel(panel1);
    public void refresh()
    gGraph._bUseTextImages = false;
    if(cbAMTS_PAID.getState())
    gGraph.setBackground(getColor(2));
    gGraph.removeAll();
    gGraph._legend.setVisible(true);
    gGraph._legend.setOrientation(14);
    gGraph._titleXAxis.setText("");
    gGraph._titleGraph.setText("");
    gGraph._axisX.setVisible(true);
    gGraph._axisY.setVisible(true);
    gGraph.setGraphType(new GraphStacked());
    gGraph.setGraphCatagories(RC.getAmountPaidCatagories());
    try
    gGraph.add(new GraphDataSeries(RC.DS_PRINCIPAL, RC.MSG_PRINCIPAL, getGraphColor(1)));
    gGraph.add(new GraphDataSeries(RC.DS_INTEREST, RC.MSG_INTEREST, getGraphColor(2)));
    gGraph._axisY._bAutoMinimum = false;
    gGraph._axisY._axisMinimum = 0.0F;
    gGraph._axisY._bAutoMaximum = false;
    gGraph._axisY._axisMaximum = (float)(RC.TOTAL_OF_PAYMENTS / (double)RC.iFactor2);
    catch(Exception _ex)
    System.out.println("Huh?");
    gGraph._titleYAxis.setText("");
    gGraph._titleGraph.setText(RC.getAmountLabel2());
    gGraph.dataChanged(true);
    } else
    gGraph.setBackground(getColor(2));
    gGraph.removeAll();
    gGraph._legend.setVisible(true);
    gGraph._legend.setOrientation(4);
    gGraph._titleXAxis.setText(RC.MSG_PAYMENT_NUMBER);
    gGraph._titleGraph.setText("");
    gGraph._titleYAxis.setText(RC.MSG_PRINCIPAL_BALANCE);
    gGraph._axisX.setVisible(true);
    gGraph._axisY.setVisible(true);
    gGraph.setGraphType(new GraphLine());
    gGraph.setGraphCatagories(RC.getCatagories());
    try
    if(cmbPREPAY_TYPE.getSelectedItem().equals(RC.PREPAY_NONE))
    gGraph.add(new GraphDataSeries(RC.DS_PRINCIPAL_BAL, RC.MSG_NORMAL_PAYMENTS, getGraphColor(1)));
    } else
    gGraph.add(new GraphDataSeries(RC.DS_PREPAY_PRINCIPAL_BAL, RC.MSG_PREPAYMENTS, getGraphColor(2)));
    gGraph.add(new GraphDataSeries(RC.DS_PRINCIPAL_BAL, RC.MSG_NORMAL_PAYMENTS, getGraphColor(1)));
    gGraph._axisY._bAutoMinimum = false;
    gGraph._axisY._bAutoMaximum = true;
    gGraph._axisY._axisMinimum = 0.0F;
    catch(Exception _ex)
    System.out.println("Huh?");
    gGraph._titleYAxis.setText(RC.getAmountLabel());
    gGraph._titleGraph.setText("");
    gGraph.dataChanged(true);
    gGraph._titleXAxis.setText(RC.MSG_YEAR_NUMBER);
    lbMONTHLY_PITI.setText(Fmt.dollars(RC.MONTHLY_PITI, 2));
    lbMONTHLY_PI.setText(Fmt.dollars(RC.MONTHLY_PI, 2));
    lbLOAN_AMOUNT.setText(Fmt.dollars(RC.LOAN_AMOUNT));
    lbTOTAL_OF_PAYMENTS.setText(Fmt.dollars(RC.PREPAY_TOTAL_OF_PAYMENTS, 2));
    lbINTEREST_PAID.setText(Fmt.dollars(RC.PREPAY_INTEREST_PAID, 2));
    lbPREPAY_INTEREST_SAVINGS.setText(Fmt.dollars(RC.PREPAY_INTEREST_SAVINGS, 2));
    setTitle("Fixed Mortgage Loan Calculator");
    public void setValues()
    throws NumberFormatException
    RC.PREPAY_TYPE = cmbPREPAY_TYPE.getSelectedItem();
    RC.PREPAY_AMOUNT = tfPREPAY_AMOUNT.toDouble();
    RC.PREPAY_STARTS_WITH = tfPREPAY_STARTS_WITH.toDouble();
    RC.INTEREST_RATE = tfINTEREST_RATE.toDouble();
    RC.YEARLY_PROPERTY_TAXES = tfYEARLY_PROPERTY_TAXES.toDouble();
    RC.YEARLY_HOME_INSURANCE = tfYEARLY_HOME_INSURANCE.toDouble();
    if(bAllTerms)
    RC.TERM = (int)tfTERM.toDouble();
    else
    RC.TERM = getMortgageTerm(cmbTERM);
    RC.LOAN_AMOUNT = tfLOAN_AMOUNT.toDouble();
    if(cbYEAR.getState())
    RC.BY_YEAR = 1;
    else
    RC.BY_YEAR = 0;
    RC.MONTHLY_PI = tfPAYMENT_PI.toDouble();
    if(RC.MONTHLY_PI > 0.0D)
    RC.PAYMENT_CALC = 0;
    else
    RC.PAYMENT_CALC = 1;
    MortgageLoanCalculation RC;
    Nbr tfINTEREST_RATE;
    Choice cmbTERM;
    Nbr tfTERM;
    boolean bAllTerms;
    Nbr tfLOAN_AMOUNT;
    Nbr tfPREPAY_AMOUNT;
    Nbr tfPREPAY_STARTS_WITH;
    Nbr tfPAYMENT_PI;
    Nbr tfYEARLY_PROPERTY_TAXES;
    Nbr tfYEARLY_HOME_INSURANCE;
    KJEChoice cmbPREPAY_TYPE;
    Label lbLOAN_AMOUNT;
    Label lbINTEREST_PAID;
    Label lbTOTAL_OF_PAYMENTS;
    Label lbMONTHLY_PI;
    Label lbMONTHLY_PITI;
    Label lbPREPAY_INTEREST_SAVINGS;
    Checkbox cbPRINCIPAL;
    Checkbox cbAMTS_PAID;
    Graph gGraph;
    Checkbox cbYEAR;
    Checkbox cbMONTH;
    }

    There are imports that aren't available to us, so no. nobody probaly can. Of course maybe someon could be bothered going through all of your code, and may spot some mistake. But I doubt they will since you didn't bother to use [c[b]ode] tags.

  • Help Please Needed for Java Calculator - ActionListener HELP

    Hi. I am constructing a simple Java calculator and need help with the actionlistener and how it could work with my program. I am not too sure how to begin constructing the actionlistener. I would like to know the best and most simple solution to get this program work the way it should, like a real calculator. If anyone can help me, that would be much appreciated.
    package calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CalculatorGUI extends JFrame implements ActionListener{
    JTextField screen;
    JButton button7;
    JButton button8;
    JButton button9;
    JButton button4;
    JButton button5;
    JButton button6;
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button0;
    JButton add;
    JButton minus;
    JButton multiply;
    JButton divide;
    JButton equals;
    JButton clear;
    private JTextField m_displayField;
    private boolean m_startNumber = true;
    private String m_previousOp = "=";
    private CalculatorLogic m_logic = new CalculatorLogic();
    public CalculatorGUI() {
    CalculatorGUILayout customLayout = new CalculatorGUILayout();
    getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
    getContentPane().setLayout(customLayout);
    screen = new JTextField("textfield_1");
    getContentPane().add(screen);
    button7 = new JButton("7");
    getContentPane().add(button7);
    button7.addActionListener(this);
    button8 = new JButton("8");
    getContentPane().add(button8);
    button8.addActionListener(this);
    button9 = new JButton("9");
    getContentPane().add(button9);
    button9.addActionListener(this);
    button4 = new JButton("4");
    getContentPane().add(button4);
    button4.addActionListener(this);
    button5 = new JButton("5");
    getContentPane().add(button5);
    button5.addActionListener(this);
    button6 = new JButton("6");
    getContentPane().add(button6);
    button6.addActionListener(this);
    button1 = new JButton("1");
    getContentPane().add(button1);
    button1.addActionListener(this);
    button2 = new JButton("2");
    getContentPane().add(button2);
    button2.addActionListener(this);
    button3 = new JButton("3");
    getContentPane().add(button3);
    button3.addActionListener(this);
    button0 = new JButton("0");
    getContentPane().add(button0);
    button0.addActionListener(this);
    add = new JButton("+");
    getContentPane().add(add);
    add.addActionListener(this);
    minus = new JButton("-");
    getContentPane().add(minus);
    minus.addActionListener(this);
    multiply = new JButton("*");
    getContentPane().add(multiply);
    multiply.addActionListener(this);
    divide = new JButton("/");
    getContentPane().add(divide);
    divide.addActionListener(this);
    equals = new JButton("=");
    getContentPane().add(equals);
    equals.addActionListener(this);
    clear = new JButton("Clear");
    getContentPane().add(clear);
    clear.addActionListener(this);
    setSize(getPreferredSize());
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void actionPerformed(ActionEvent event) {
    public static void main(String args[]) {
    CalculatorGUI window = new CalculatorGUI();
    window.setTitle("Calculator");
    window.pack();
    window.show();
    class CalculatorGUILayout implements LayoutManager {
    public CalculatorGUILayout() {
    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 = 421 + insets.left + insets.right;
    dim.height = 494 + 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,408,64);}
    c = parent.getComponent(1);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+80,96,56);}
    c = parent.getComponent(2);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+80,96,56);}
    c = parent.getComponent(3);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+80,96,56);}
    c = parent.getComponent(4);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+144,96,56);}
    c = parent.getComponent(5);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+144,96,56);}
    c = parent.getComponent(6);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+144,96,56);}
    c = parent.getComponent(7);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+208,96,56);}
    c = parent.getComponent(8);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+208,96,56);}
    c = parent.getComponent(9);
    if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+208,96,56);}
    c = parent.getComponent(10);
    if (c.isVisible()) {c.setBounds(insets.left+120,insets.top+272,96,56);}
    c = parent.getComponent(11);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+80,72,56);}
    c = parent.getComponent(12);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+144,72,56);}
    c = parent.getComponent(13);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+208,72,56);}
    c = parent.getComponent(14);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+272,72,56);}
    c = parent.getComponent(15);
    if (c.isVisible()) {c.setBounds(insets.left+344,insets.top+336,72,56);}
    c = parent.getComponent(16);
    if (c.isVisible()) {c.setBounds(insets.left+8,insets.top+408,408,72);}
    }

    Yeah, I have a rough idea of what the calculator
    should do, like most people would. Its just that I
    dont know how to implement this in Java. Thats the
    problem. Can anyone provide me with code snippets
    that I can try?No I would rather see you make an effort from what has been discussed here. This is not a Java problem this is a general programming problem.

  • Error when running mortgage calc program from DOS prompt

    I have a GUI Mortgage Calculator program. It probably isn't the most efficient use of code, but it gets the job done. I am running java SDK 1.6.0_06. This is a class assignment. We are to compile the code and post the .class file for our team members to run. I am trying to get the .class file to run after I compile it with javac. I used jCreator LE to create it... it compiles and runs there just fine. The program will compile at the DOS prompt, but will not run properly. The following is the error I get (any help would be appreciated):
    Exception in thread "mani" java.lang.NoClassDefFoundError: manchorMortgage3
    Caused by: java.lang.ClassNotFoundException: manchorMortgage3
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader1.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Below is my code:
    * manchorMortgage3.java
    * Created on July 10, 2008
    * This program calculates and displays the mortgage amount
    * from user input of the amount of the mortgage and the user's
    * selection from a menu of available mortgage loans.
    import java.math.*; //*loan calculator
    import java.text.*; //*formats numbers
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class manchorMortgage3 extends javax.swing.JFrame {
        /** Creates new form manchorMortgage3 */
             public manchorMortgage3() {
             initComponents();
             setLocation(300,200);
        /** This method is called from within the constructor to
         * initialize the form.
        // Begin Initialize Components
        private void initComponents() {
            mortgageAmount = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            termAndInterest = new javax.swing.JLabel();
            jRadioButton1 = new javax.swing.JRadioButton();
            jRadioButton2 = new javax.swing.JRadioButton();
            jRadioButton3 = new javax.swing.JRadioButton();
            calcButton = new javax.swing.JButton();
            enterAmount = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jButton2 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Manchor - Mortgage Calculator - Week 3");
            mortgageAmount.setText("Enter the Mortgage Amount:");
            termAndInterest.setText("Select Your Term and Interest Rate:");
            jRadioButton1.setText("7 years at 5.35%");
            jRadioButton1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton1.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton1ActionPerformed(evt);
            jRadioButton2.setText("15 years at 5.5%");
            jRadioButton2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton2.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton2ActionPerformed(evt);
            jRadioButton3.setText("30 years at 5.75%");
            jRadioButton3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jRadioButton3.setMargin(new java.awt.Insets(0, 0, 0, 0));
            jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton3ActionPerformed(evt);
            calcButton.setText("Calculate");
            calcButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    calcButtonActionPerformed(evt);
            jTextArea1.setColumns(20);
            jTextArea1.setEditable(false);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
            jButton2.setText("Quit");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(enterAmount)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 222, Short.MAX_VALUE)
                                .addComponent(calcButton)
                                .addGap(75, 75, 75))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jRadioButton3)
                                    .addComponent(jRadioButton2)
                                    .addComponent(jRadioButton1)
                                    .addComponent(termAndInterest)
                                    .addComponent(mortgageAmount)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(224, Short.MAX_VALUE)))))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(277, Short.MAX_VALUE)
                    .addComponent(jButton2)
                    .addGap(70, 70, 70))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(31, 31, 31)
                    .addComponent(mortgageAmount)
                    .addGap(14, 14, 14)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(20, 20, 20)
                    .addComponent(termAndInterest)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jRadioButton1)
                    .addGap(15, 15, 15)
                    .addComponent(jRadioButton2)
                    .addGap(19, 19, 19)
                    .addComponent(jRadioButton3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(calcButton)
                        .addComponent(enterAmount))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton2)
                    .addGap(20, 20, 20))
            pack();
        }// End initialize components
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//event_jButton2ActionPerformed
            System.exit(1);
        }//event_jButton2ActionPerformed
        static NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
        static NumberFormat np = NumberFormat.getPercentInstance();
        static NumberFormat ni = NumberFormat.getIntegerInstance();
        static BufferedReader br;
        private void calcButtonActionPerformed(java.awt.event.ActionEvent evt) {//event_calcButtonActionPerformed
            enterAmount.setText(null);
            jTextArea1.setText(null);
            double monthlyPayment;
            double interest;
            double amount ;       
            int years ;
            double monthlyInterest, monthlyPrinciple, principleBalance;
            int paymentsRemaining, lineCount;
            np.setMinimumFractionDigits(2);
        br = new BufferedReader(new InputStreamReader(System.in));
      lineCount = 0;
            try
                    amount=Double.parseDouble(jTextField1.getText());
            catch (Exception e)
                enterAmount.setText("Please Enter Mortgage Amount");
                return;
            if(jRadioButton1.isSelected())
                interest=0.0535;
                years=7;
            else if(jRadioButton2.isSelected())
                interest=0.055;
                years=15;
            else if(jRadioButton3.isSelected())
                interest=0.0575;
                years=30;
            else
                enterAmount.setText("Please Select Your Term and Interest Rate");
                return;
        jTextArea1.append(" For a mortgage of " + nf.format(amount)+"\n"+" With a Term of " + ni.format(years) + " years"+"\n"+" And an Interest rate of " + np.format(interest)+"\n"+" The Payment Amount is " + nf.format(getMortgagePmt(amount, years, interest)) + " per month."+"\n"+"\n");
        principleBalance = amount - ((getMortgagePmt(amount, years, interest)) - (amount*(interest/12)));
        paymentsRemaining = 0;
        do
            monthlyInterest = principleBalance * (interest/12);//*Current monthly interest
             monthlyPrinciple = (getMortgagePmt(amount, years, interest)) - monthlyInterest;//*Principal payment each month minus interest
            paymentsRemaining = paymentsRemaining + 1;
            principleBalance = principleBalance - monthlyPrinciple;//*New balance of loan
            jTextArea1.append(" Principal on payment  " + ni.format(paymentsRemaining) + " is " + nf.format(monthlyPrinciple)+"\n");
                    jTextArea1.append(" Interest on payment  " + ni.format(paymentsRemaining) + " is " + nf.format(monthlyInterest)+"\n");
                    jTextArea1.append(" New loan balance on payment  " + ni.format(paymentsRemaining) + " is " + nf.format(principleBalance)+"\n"+"\n"+"\n");
         while (principleBalance > 1);
        }//Begin event_jRadioBtton1Action Performed
        public static double getMortgagePmt(double balance, double term, double rate)
                double monthlyRate = rate / 12;
                double monthlyPayment = (balance * monthlyRate)/(1-Math.pow(1+monthlyRate, - term * 12));
                return monthlyPayment;
        private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//Begin event_jRadioButton3ActionPerformed
             if(jRadioButton2.isSelected())
                jRadioButton2.setSelected(false);
             if(jRadioButton1.isSelected())
                jRadioButton1.setSelected(false);
        }//End event_jRadioButton3ActionPerformed
        private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//Begin event_jRadioButton2ActionPerformed
             if(jRadioButton1.isSelected())
                jRadioButton1.setSelected(false);
             if(jRadioButton3.isSelected())
                jRadioButton3.setSelected(false);
        }//End event_jRadioButton2ActionPerformed
        private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
            if(jRadioButton2.isSelected())
                jRadioButton2.setSelected(false);
            if(jRadioButton3.isSelected())
                jRadioButton3.setSelected(false);
        }//End event_jRadioButton1ActionPerformed
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new manchorMortgage3().setVisible(true);
        // Begin variables declaration
        private javax.swing.JButton calcButton;
        private javax.swing.JButton jButton2;
        private javax.swing.JLabel mortgageAmount;
        private javax.swing.JLabel termAndInterest;
        private javax.swing.JLabel enterAmount;
        private javax.swing.JRadioButton jRadioButton1;
        private javax.swing.JRadioButton jRadioButton2;
        private javax.swing.JRadioButton jRadioButton3;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        private javax.swing.JTextField jTextField1;
        // End  variables declaration
    }

    The class is not in your classpath. Likely you blew away your classpath with some silly environment variable.
    If you are in the directory where your class file is then execute
    java -cp . manchorMortgage3and it will work. (Note the -cp . which tells java to include the current directory in the runtime classpath)

  • I need an Array in my JAVA CODE

    I need an array in my java code for my last class in my Java 1 course
    my code does compile in dos using javac,....and it does work
    It is a mortgage calculator for 3 loans of 3 different years loaned,.... and each have a different interest rate.
    I need to have my code in an ARRAY for my last week .
    any help would be appreciated
    here is my code :
    import java.text.*;           //20 May 2008, Revision ...many
    import java.io.IOException;
    class memortgage     //program class name
      public static void main(String[] args) throws IOException
        double amount,moPay,totalInt,principal = 200000; //monthly payment, total interest and principal
        double rate [ ] = {.0535, .055, .0575};          //the three interest rates
        int [ ] term = {7,15,30};                        //7, 15 and 30 year term loans
        int time,ratePlace = 0,i,pmt=1,firstIterate = 0,secondIterate = 0,totalMo=0;
        char answer,test;
        boolean validChoice;
        System.in.skip(System.in.available());           //clear the stream for the next entered character
        do
          validChoice = true;
          System.out.println("What Choice would you Like\n");
          System.out.println("1-Interest rate of 5.35% for 7 years?");       //just as it reads for each to select from
          System.out.println("2-Interest rate of 5.55% for 15 years?");
          System.out.println("3-Interest rate of 5.75% for 30 years?");
          System.out.println("4-Quit");
          answer = (char)System.in.read();
          if (answer == '1')  //7 yr loan at 5.35%
            ratePlace = 0;
            firstIterate = 4;
            secondIterate = 21;
            totalMo= 84;
          else if (answer == '2') //15 yr loan at 5.55%
            ratePlace = 1;
            firstIterate = 9;      //it helps If I have the correct numbers to calcualte as in 9*20 to equal 180...that why I was off -24333.76
            secondIterate = 20;    //now it is only of -0.40 cents....DAMN ME
            totalMo = 180;
          else if (answer == '3') //30 yr loan at 5.75%
            ratePlace = 2;
            firstIterate = 15;
            secondIterate = 24;
            totalMo = 360;
          else if (answer == '4') //exit or quit
            System.exit(0);
          else
            System.in.skip(System.in.available());               //validates choice
            System.out.println("Invalid choice, try again.\n\n");
            validChoice = false;
        }while(!validChoice);  //when a valid choice is found calculate the following, ! means not, similar to if(x != 4)
        for(int x = 0; x < 25; x++)System.out.println();
        amount = (principal + (principal * rate[ratePlace] * term[ratePlace] ));
        moPay = (amount / totalMo);
        totalInt = (principal * rate[ratePlace] * term[ratePlace]);
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println("The Interest on $" + (df.format(principal) + " at " + rate[ratePlace]*100 +
        "% for a term of "+term[ratePlace]+" years is \n" +"$"+ (df.format(totalInt) +" Dollars\n")));
        System.out.println("\nThe total amount of loan plus interest is $"+(df.format(amount)+" Dollars.\n"));
        System.out.println("\nThe Payments spread over "+term[ratePlace]* 12+" months would be $"+
        (df.format (moPay) + " Dollars a month\n\n"));
        System.in.skip(System.in.available());
        System.out.println("\nWould you like to see a planned payment schedule? y for Yes, or x to Exit");
        answer = (char)System.in.read();
        if (answer == 'y')
          System.out.println((term[ratePlace]*12) + " monthly payments:");
          String monthlyPayment = df.format(moPay);
          for (int a = 1; a <= firstIterate; a++)
            System.out.println(" Payment Schedule \n\n ");
            System.out.println("Month Payment Balance\n");
            for (int b = 1; b <= secondIterate; b++)
              amount -= Double.parseDouble(monthlyPayment);
              System.out.println(""+ pmt++ +"\t"+ monthlyPayment + "\t"+df.format(amount));
            System.in.skip(System.in.available());
            System.out.println(("This Page Is Complete Press [ENTER] to Continue"));
            System.in.read();
    }

    here is what was commented from my instructor for my week 4...is what you sen in the code....but I fixed loan 2 tonight
    "Week 4 Great work, the numbers were a little off on the 1st and 2nd loans. Next time
    try putting the values you displayed in an array. "
    import java.text.*;           //20 May 2008, Revision ...many
    import java.io.IOException;
    class memortgage     //program class name
      public static void main(String[] args) throws IOException
        double amount,moPay,totalInt,principal = 200000; //monthly payment, total interest and principal
        double rate [ ] = {.0535, .055, .0575};          //the three interest rates
        int [ ] term = {7,15,30};                        //7, 15 and 30 year term loans
        int time,ratePlace = 0,i,pmt=1,firstIterate = 0,secondIterate = 0,totalMo=0;
        char answer,test;
        boolean validChoice;
        System.in.skip(System.in.available());           //clear the stream for the next entered character
        do
          validChoice = true;
          System.out.println("What Choice would you Like\n");
          System.out.println("1-Interest rate of 5.35% for 7 years?");       //just as it reads for each to select from
          System.out.println("2-Interest rate of 5.55% for 15 years?");
          System.out.println("3-Interest rate of 5.75% for 30 years?");
          System.out.println("4-Quit");
          answer = (char)System.in.read();
          if (answer == '1')  //7 yr loan at 5.35%
            ratePlace = 0;
            firstIterate = 4;
            secondIterate = 21;
            totalMo= 84;
          else if (answer == '2') //15 yr loan at 5.55%
            ratePlace = 1;
            firstIterate = 9;      //it helps If I have the correct numbers to calcualte as in 9*20 to equal 180...that why I was off -24333.76
            secondIterate = 20;    //now it is only of -0.40 cents....DAMN ME
            totalMo = 180;
          else if (answer == '3') //30 yr loan at 5.75%
            ratePlace = 2;
            firstIterate = 15;
            secondIterate = 24;
            totalMo = 360;
          else if (answer == '4') //exit or quit
            System.exit(0);
          else
            System.in.skip(System.in.available());               //validates choice
            System.out.println("Invalid choice, try again.\n\n");
            validChoice = false;
        }while(!validChoice);  //when a valid choice is found calculate the following, ! means not, similar to if(x != 4)
        for(int x = 0; x < 25; x++)System.out.println();
        amount = (principal + (principal * rate[ratePlace] * term[ratePlace] ));
        moPay = (amount / totalMo);
        totalInt = (principal * rate[ratePlace] * term[ratePlace]);
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println("The Interest on $" + (df.format(principal) + " at " + rate[ratePlace]*100 +
        "% for a term of "+term[ratePlace]+" years is \n" +"$"+ (df.format(totalInt) +" Dollars\n")));
        System.out.println("\nThe total amount of loan plus interest is $"+(df.format(amount)+" Dollars.\n"));
        System.out.println("\nThe Payments spread over "+term[ratePlace]* 12+" months would be $"+
        (df.format (moPay) + " Dollars a month\n\n"));
        System.in.skip(System.in.available());
        System.out.println("\nWould you like to see a planned payment schedule? y for Yes, or x to Exit");
        answer = (char)System.in.read();
        if (answer == 'y')
          System.out.println((term[ratePlace]*12) + " monthly payments:");
          String monthlyPayment = df.format(moPay);
          for (int a = 1; a <= firstIterate; a++)
            System.out.println(" Payment Schedule \n\n ");
            System.out.println("Month Payment Balance\n");
            for (int b = 1; b <= secondIterate; b++)
              amount -= Double.parseDouble(monthlyPayment);
              System.out.println(""+ pmt++ +"\t"+ monthlyPayment + "\t"+df.format(amount));
            System.in.skip(System.in.available());
            System.out.println(("This Page Is Complete Press [ENTER] to Continue"));
            System.in.read();
    }

  • Need help with Java, have a few questions about my Applet

    Purpose of the program: To create a mortgage calculator that will allow the user to input the loan principal then select 1 of 3 choices from a combo-box (7 years @ 5.35%, 15 years @ 5.50%, 30 years @ 5.75%).
    Problem: My program was working properly (so I thought). I can get the program to properly compile and run through TextPad. However, I noticed that when the user clicks the calculate more than once (with the same input), it slightly alters the output calculations. So that is my first question, Why is it doing that?  How can I get it only calculate that information once unless the user changes it etc?
    My next question is regarding my exit button. I was told by my instructor (who has already stated he won't help any of us) that my exit button does not work for an applet and only for an application. So, how can I create an exit button that will work with an applet? I thought I did it right but I can't find any resources online for this.
    Next question, why isn't my program properly validating invalid input? My program should only allow numeric input and nothing more.
    And last question, when invalid input is entered and the user clicks calculate, why isn't my JOptionPane window for error messages not displaying?
    I know my code is a little long so I have to post this in two messages. Please don't criticize me for what I am doing, that is why I am learning and have come to this forum for help. Thanks
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    // Creating the main class
    public class test extends JApplet implements ActionListener
         // Defining of format information
         JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
         Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
         Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
         Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
         Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
         JButton calculate = new JButton("Calculate");
         JButton exitButton = new JButton("Quit");
         JButton clearButton = new JButton("Clear");
         JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
         JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
         // Declaration of variables
         private double principalAmount;
         private JLabel principalLabel = new JLabel("Principal Amount");
         private NumberFormat principalFormat;
         private JTextField enterPrincipal = new JTextField(10);
         private double finalPayment;
         private JLabel monthlyPaymentLabel = new JLabel("  Monthly Payment    \t         Interest Paid    \t \t            Loan Balance");
         private NumberFormat finalPaymentFormat;
         private JTextField displayMonthlyPayment = new JTextField(10);
         private JTextField displayInterestPaid = new JTextField(10);
         private JTextField displayBalance = new JTextField(10);
         // Creation of the String of arrays for the ComboBox
         String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
         JComboBox selections = new JComboBox(list);
         // Creation of the textArea that will display the output
         private TextArea txtArea = new TextArea(5, 10);
         StringBuffer buff = null;
              Edited by: LoveMyAJ on Jan 19, 2009 1:49 AM

    // Initializing the interface
         public void init()
              // Creation of the panel design and fonts
              JPanel upper = new JPanel(new BorderLayout());
              JPanel middle = new JPanel(new BorderLayout());
              JPanel lower = new JPanel(new BorderLayout());
              JPanel areaOne = new JPanel(new BorderLayout());
              JPanel areaTwo = new JPanel(new BorderLayout());
              JPanel areaThree = new JPanel(new BorderLayout());
              JPanel areaFour = new JPanel(new BorderLayout());
              JPanel areaFive = new JPanel(new BorderLayout());
              JPanel areaSix = new JPanel(new BorderLayout());
              Container con = getContentPane();
              getContentPane().add(upper, BorderLayout.NORTH);
              getContentPane().add(middle, BorderLayout.CENTER);
              getContentPane().add(lower, BorderLayout.SOUTH);
              upper.add(areaOne, BorderLayout.NORTH);
              middle.add(areaTwo, BorderLayout.NORTH);
              middle.add(areaThree, BorderLayout.CENTER);
              middle.add(areaFour, BorderLayout.SOUTH);
              lower.add(areaFive, BorderLayout.NORTH);
              lower.add(areaSix, BorderLayout.SOUTH);
              heading.setFont(newFontOne);
              instructions.setFont(newFontTwo);
              instructions2.setFont(newFontTwo);
              principalLabel.setFont(newFontThree);
              monthlyPaymentLabel.setFont(newFontFour);
              displayInterestPaid.setFont(newFontFour);
              displayBalance.setFont(newFontFour);
              areaOne.add(heading, BorderLayout.NORTH);
              areaOne.add(instructions, BorderLayout.CENTER);
              areaOne.add(instructions2, BorderLayout.SOUTH);
              areaTwo.add(principalLabel, BorderLayout.WEST);
              areaTwo.add(enterPrincipal, BorderLayout.EAST);
              areaThree.add(selections, BorderLayout.NORTH);
              areaFour.add(calculate, BorderLayout.CENTER);
              areaFour.add(exitButton, BorderLayout.EAST);
              areaFour.add(clearButton, BorderLayout.WEST);
              areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
              areaSix.add(txtArea, BorderLayout.CENTER);
              // Using the ActionListener to determine when each button is clicked
              calculate.addActionListener(this);
              exitButton.addActionListener(this);
              clearButton.addActionListener(this);
              enterPrincipal.requestFocus();
              selections.addActionListener(this);
         // The method that will perform specific actions defined below
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              buff = new StringBuffer();
              // Outcome of pressing the calculate button
              if (source == calculate)
                   // Used to call upon the user chosen selection
                   int selection = selections.getSelectedIndex();
                   // If statement to call upon Loan One's Method
                   if (selection == 0)
                        Double data = (Double)calculateLoanOne();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Two's Method
                   else if (selection == 1)
                        Double data = (Double)calculateLoanTwo();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // If statement to call upon Loan Three's Method
                   else if (selection == 2)
                        Double data = (Double)calculateLoanThree();
                        String sourceInput = data.toString();
                        displayMonthlyPayment.setText(sourceInput);
                        txtArea.setText(buff.toString());
                   // Outcome of pressing the clear button
                   else if (source == clearButton)
                        enterPrincipal.setText("");
                        displayMonthlyPayment.setText("");
                        selections.setSelectedIndex(0);
                        txtArea.setText("");
                   // Outcome of pressing the quit button
                   else if (source == exitButton)
                        System.exit(1);
         // Method used to validate user input
         private static boolean validate(JTextField in)
              String inText = in.getText();
              char[] charInput = inText.toCharArray();
              for(int i = 0; i < charInput.length; i++)
                   int asciiVal = (int)charInput;
              if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
              else
                   JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
                   return false;
                   return true;

  • Invalid characters displayed in java-based tool

    I'm having problems with a java applet that works fine on the vast majority of PCs, with 1 exception. The one in question runs Windows 7 32 bit professional, IE8. Java versions 27,29, and 31 have been tried, with the same results.
    There are several fields, each of which has a title and a default value. On a working PC, the field names are:
    Mortgage amount:
    Term:
    Interest rate:
    Monthly payment (PI):
    Annual property taxes:
    Annual home insurance:
    Monthly payment (PITI):
    On a PC that its not working:
    Kn` mHmendl `shmm9
    Lnqsf` fd `l nt ms9
    Hmsdqdrsq` sd9
    Lnmaglx o` xl dms` OH(9
    @mt ` koqnodqsx s wdr 9
    @mt ` kgnl d hmtq` mbd9
    L nmaglx o`xl dms ' OHSH(9#371-1/
    There are more fields, but that's an example. it may not be exactly correct, since the spacing and character overlap makes it hard to differentiate some characters.
    All the browser troubleshooting has been done (reset, cleared temps, deleted active X objects etc.)
    Cleared all local cache, java cache and ran ccleaner
    Checked Windows region, language, currency etc settings
    Tried to reinstall java, tried 3 different versions (27, 29, 31)
    Tried the local Admin profile and problem persists across multiple profiles.
    If anyone has any ideas about which settings could possibly cause this character translation, I would be very appreciative. There appers to be a 1:1 correlation of characters, for example:
    # = $
    / = 0
    : = 9
    R = S
    Could it be some kind of java / unicode setting?

    If I could post a picture it might help explain...
    http://postimage.org/image/qtl15mdoz/
    Uploaded, hopefully you can view it.
    We've reset the browser, even tried IE9, with the same result. There's no toolbars installed and machine tested clean for adware. With no java installed, the webpage displays sans mortgage calculator. What seems strange is that some of the text displays properly, as you can see in the picture, so that's why I wonder if its just one particular font that's not being displayed properly? The entire rest of the web page, and everything else that uses java works fine, it seems like it's just this one particular calculator.
    It's at the point where the OS may just need to be reinstalled, though it seems like a small, petty thing to reinstall the OS for... but without a solution i don't really have any other options.

Maybe you are looking for