Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Missing a brace or something with Java

Posted on 2011-09-26
5
Medium Priority
?
305 Views
Last Modified: 2012-08-13
I am trying to create a mortgage calculator in Java (with a graphical user interface) and have it calculate and display the mortgage payment amount from user input of the amount of the mortgage and the user's selection from a menu of available mortgage loans:

- 7 years at 5.35%
- 15 years at 5.5%
- 30 years at 5.75%

I am using an array for the mortgage data for the different loans. I am trying to display the mortgage payment amount followed by the loan balance and interest paid for each payment over the term of the loan. I am also trying to allow the user to loop back and enter a new amount and make a new selection or quit.

So I've gotten the code completed, but I'm getting errors.  I'm not sure if I've intended somewhere I shouldn't have, or what.  

Seems if I add a brace, all sorts of other things go wrong.  What did I do wrong?

Thank you.
   
import java.awt.Dimension;
import java.awt.BorderLayout;           // Import and Provide Layout of Window
import java.awt.GridLayout;		// Import the Layout in Grid Format
import java.awt.event.ActionEvent;      // Import Action
import java.awt.event.ActionListener;   // Import Listener for Action
import javax.swing.JButton;             // Import Use of Buttons
import javax.swing.JFrame;		// Import Use of Frame
import javax.swing.JLabel;		// Import Use of Label
import javax.swing.JPanel;		// Import Use of Panel
import javax.swing.JTextField;		// Import Use of Text Field
import javax.swing.JTextArea;		// Import Use of Text Area
import javax.swing.JScrollPane;         // Import Scroll Pane
import javax.swing.JComboBox;           // Import JCombo Box
import java.text.DecimalFormat;         // Import Decimal Format to Eliminate Extra Places Past Decimal Point

//Creating the Mortgage Payment Class
public class sr_mf_03_cr5 extends JFrame
{
    DecimalFormat Dollar = new DecimalFormat("$000,000.00");
	//GUI elements to display current information
	private JLabel loanamountLabel = new JLabel("Initial Loan Amount");
	private JTextField LoanAmountTextField = new JTextField (20);

	private JLabel interestrateLabel = new JLabel("Interest Rate");

	String interestrate[] = {"Select Interest Rate","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};

	private JComboBox combo = new JComboBox(interestrate);

	 private JTextArea result = new JTextArea(10, 20);
    JScrollPane scrollingResult = new JScrollPane(result);

	public sr_mf_03_cr5() {

		//building the panel for the buttons
		JPanel buttonPanel = new JPanel();

		//creating the "calculate" button
		 JButton btncalc = new JButton("Calculate");
		 btncalc.addActionListener(new ActionListener()
		 {
			public void actionPerformed(ActionEvent event)
			{
				onButtoncalc();
			}
		});
		//creating the "Reset" button
		JButton btnreset = new JButton("Reset");
		btnreset.addActionListener(new ActionListerner()
		{
			public void actionPerformed(ActionEvent event)
			{
				onButtonreset();
			}
		});
		//create the panel
		JPanel centerPanel = new JPanel();
		//set the layout
		centerPanel.setLayout(new GridLayout(3, 2,3,3));

		//add the components
		centerPanel.add(loanamountLabel);
		centerPanel.add(loanamounttext);
		centerPanel.add(interestlLabel);
		centerPanel.add(combo);

		centerPanel.add(btncalc);
		centerPanel.add(btnreset);

		setLayout(new BorderLayout());

        centerPanel.setPreferredSize(new Dimension(500,200));

        //adding to the frame
		        add(centerPanel, BorderLayout.CENTER);
		        add(scrollingResult, BorderLayout.SOUTH);

		        //setting the frame properties
		        pack();
		        setDefaultCloseOperation(EXIT_ON_CLOSE );
        //setResizable(false);
        setTitle("Mortgage Calculator");
        setVisible(true);
    }

    //calculate information
    public void onButtonCalc(){
		//getting the values
		double loanAmount=Double.parseDouble(loanamountText.getText());
		double interestrate=0.0;
		int loanterm=0;
 String str = (String)combo.getSelectedItem();
	if(str.equals("7 years at 5.35%"))
	{
            interesrate = 5.35 ;
            loanterm = 7 ;
	}
	else
	if(str.equals("15 years at 5.5%"))
	{
            interestrate = 5.5 ;
            loanterm = 15 ;
	}
	else
	if(str.equals("30 years at 5.75%"))
	{
            interestrate = 5.75 ;
            loanterm = 30 ;
	}

	//creating the new loan
	Loan loan = new Loan(loanAmount, interestrate, loanterm);

	//setting the result text
	        result.setText("Loan Amount = " + Dollar.format(loanAmount)
	    		+"\nInterest Rate = " + interestrate +"%"+"\nLength of Loan = "
	    		+ Math.round(loanterm* 12.0) + " months"+"\nMonthly Payment = "
	    		+ Dollar.format(loan.CalcMonthlyPayment())
	                + loan.MonthlyloanAmount());//calling the ComputeMonthlyPayment() method of loan class
    }

	//Information for Reset Button
	public void onButtonReset(){

		//resetting fields
		loanamountText.setText("");
			combo.setSelectedIndex(0);
		        result.setText("");
    }
    public static void main(String[] args){

		sr_mf_03_cr5 newloan = new sr_mf_03_cr5();   //creating an instance of the class
	}
}
//creating a class to store the loan data
class Loan {
	double LoanAmount; //original amount of the loan
	double Interest; //interest rate of the loan as a percent
	int LoanTerm;  //Term of the loan, expressed in years

 DecimalFormat Dollar = new DecimalFormat("000,000.00");

 public Loan(double LoanAmount, double Interst, int LoanTerm)
	{
		this.LoanAmount = LoanAmount;
		this.Interest = Interest;
		this.LoanTerm = LoanTerm;
	}

	//calculate the monthly payment
	public double Calculatemonthlypayment() {

		//setting the values before calculations are peformed
		double monthlyinterest = 0;  //ammount of interest paid each month
		double numberofpayments = 0; //number of payments remaining

		monthlyinterest = Calculatemonthlyinterest(Interest);
		numberofpayment = LoanTerm*12;
		return (LoanAMount * monthlyinterest) / (1.0-(Math.pow((1.0 + monthlyinterest),-numberofpayments)));
	}

	//caclulate the monthly interest
	public double Calculatemonthlyinterest(double Interest) {
		return Interest  / (100 * 12);
	}
	public String LoanAmountRemaining() {
		String result = "\n\n,onth\tloanbalance\tinterest paid\n";
		double terminmonths = LoanTerm * 12;  //converts the loan term from years to months
		double newterminmonths = terminmonths;	  //setting the variables up so that the number of months remaining on the loan (thus the remainder of monthly payments can be calculated

		//setting up while loop
		while (newterminmonths > 0) {

			double loanmonths = terminmonths-newterminmonths;  //calculating the amount of months left on the term
			double loanbalance = LoanAmount*((Math.pow((1 + Calculatemonthlyinterest(Interest)),loanTerm))-(Math.pow((1 + Calculatemonthlyinterest(Interest)),loanMonths)))/(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)-1);  //calculating the remaining balance of the loan
			double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);  //calculating the amount of interest paid each month


		result+=(""+Math.round(newterminmonths) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");
		newterminmonths = newterminmonths - 1;  //calculating the remaining months left on the loan
	}
		return result;
  }

Open in new window

0
Comment
Question by:Winstink
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 37

Expert Comment

by:TommySzalapski
ID: 36601957
What does the error say and what line does it point to?
Also, when you add the brace what is the first error when "all sorts of other things go wrong"
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36602026

This code at least compiles

There were all sorts of mismatches:

java is case sensitive - you cannot arrbitraty change case in the variables - there weer many pf them

/* Tim Hatch
 * sr_mf_003_cr5.java
 * September 26, 2011
 */

import java.awt.Dimension;
import java.awt.BorderLayout;           // Import and Provide Layout of Window
import java.awt.GridLayout;		// Import the Layout in Grid Format
import java.awt.event.ActionEvent;      // Import Action
import java.awt.event.ActionListener;   // Import Listener for Action
import javax.swing.JButton;             // Import Use of Buttons
import javax.swing.JFrame;		// Import Use of Frame
import javax.swing.JLabel;		// Import Use of Label
import javax.swing.JPanel;		// Import Use of Panel
import javax.swing.JTextField;		// Import Use of Text Field
import javax.swing.JTextArea;		// Import Use of Text Area
import javax.swing.JScrollPane;         // Import Scroll Pane
import javax.swing.JComboBox;           // Import JCombo Box
import java.text.DecimalFormat;         // Import Decimal Format to Eliminate Extra Places Past Decimal Point

//Creating the Mortgage Payment Class
public class sr_mf_03_cr5 extends JFrame
{
    DecimalFormat Dollar = new DecimalFormat("$000,000.00");
	//GUI elements to display current information
	private JLabel loanamountLabel = new JLabel("Initial Loan Amount");
	private JTextField LoanAmountTextField = new JTextField (20);

	private JLabel interestrateLabel = new JLabel("Interest Rate");

	String interestrate[] = {"Select Interest Rate","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};

	private JComboBox combo = new JComboBox(interestrate);

	 private JTextArea result = new JTextArea(10, 20);
    JScrollPane scrollingResult = new JScrollPane(result);

	public sr_mf_03_cr5() {

		//building the panel for the buttons
		JPanel buttonPanel = new JPanel();

		//creating the "calculate" button
		 JButton btncalc = new JButton("Calculate");
		 btncalc.addActionListener(new ActionListener()
		 {
			public void actionPerformed(ActionEvent event)
			{
				onButtonCalc();
			}
		});
		//creating the "Reset" button
		JButton btnreset = new JButton("Reset");
		btnreset.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				onButtonReset();
			}
		});
		//create the panel
		JPanel centerPanel = new JPanel();
		//set the layout
		centerPanel.setLayout(new GridLayout(3, 2,3,3));

		//add the components
		centerPanel.add(loanamountLabel);
		centerPanel.add(LoanAmountTextField);
		centerPanel.add(interestrateLabel);
		centerPanel.add(combo);

		centerPanel.add(btncalc);
		centerPanel.add(btnreset);

		setLayout(new BorderLayout());

        centerPanel.setPreferredSize(new Dimension(500,200));

        //adding to the frame
		        add(centerPanel, BorderLayout.CENTER);
		        add(scrollingResult, BorderLayout.SOUTH);

		        //setting the frame properties
		        pack();
		        setDefaultCloseOperation(EXIT_ON_CLOSE );
        //setResizable(false);
        setTitle("Mortgage Calculator");
        setVisible(true);
    }

    //calculate information
    public void onButtonCalc(){
		//getting the values
		double loanAmount=Double.parseDouble(LoanAmountTextField.getText());
		double interestrate=0.0;
		int loanterm=0;
 String str = (String)combo.getSelectedItem();
	if(str.equals("7 years at 5.35%"))
	{
            interestrate = 5.35 ;
            loanterm = 7 ;
	}
	else
	if(str.equals("15 years at 5.5%"))
	{
            interestrate = 5.5 ;
            loanterm = 15 ;
	}
	else
	if(str.equals("30 years at 5.75%"))
	{
            interestrate = 5.75 ;
            loanterm = 30 ;
	}

	//creating the new loan
	Loan loan = new Loan(loanAmount, interestrate, loanterm);

	//setting the result text
	        result.setText("Loan Amount = " + Dollar.format(loanAmount)
	    		+"\nInterest Rate = " + interestrate +"%"+"\nLength of Loan = "
	    		+ Math.round(loanterm* 12.0) + " months"+"\nMonthly Payment = "
	    		+ Dollar.format(loan.Calculatemonthlypayment())
	                + loan.LoanAmountRemaining());//calling the ComputeMonthlyPayment() method of loan class
    }

	//Information for Reset Button
	public void onButtonReset(){

		//resetting fields
		LoanAmountTextField.setText("");
			combo.setSelectedIndex(0);
		        result.setText("");
    }
    public static void main(String[] args){

		sr_mf_03_cr5 newloan = new sr_mf_03_cr5();   //creating an instance of the class
	}
}
//creating a class to store the loan data
class Loan {
	double LoanAmount; //original amount of the loan
	double Interest; //interest rate of the loan as a percent
	int LoanTerm;  //Term of the loan, expressed in years

 DecimalFormat Dollar = new DecimalFormat("000,000.00");

 public Loan(double LoanAmount, double Interst, int LoanTerm)
	{
		this.LoanAmount = LoanAmount;
		this.Interest = Interest;
		this.LoanTerm = LoanTerm;
	}

	//calculate the monthly payment
	public double Calculatemonthlypayment() {

		//setting the values before calculations are peformed
		double monthlyinterest = 0;  //ammount of interest paid each month
		double numberofpayments = 0; //number of payments remaining

		monthlyinterest = Calculatemonthlyinterest(Interest);
		numberofpayments = LoanTerm*12;
		return (LoanAmount * monthlyinterest) / (1.0-(Math.pow((1.0 + monthlyinterest),-numberofpayments)));
	}

	//caclulate the monthly interest
	public double Calculatemonthlyinterest(double Interest) {
		return Interest  / (100 * 12);
	}
	public String LoanAmountRemaining() {
		String result = "\n\n,onth\tloanbalance\tinterest paid\n";
		double terminmonths = LoanTerm * 12;  //converts the loan term from years to months
		double newterminmonths = terminmonths;	  //setting the variables up so that the number of months remaining on the loan (thus the remainder of monthly payments can be calculated

		//setting up while loop
		while (newterminmonths > 0) {

			double loanmonths = terminmonths-newterminmonths;  //calculating the amount of months left on the term
			double loanbalance = LoanAmount*((Math.pow((1 + Calculatemonthlyinterest(Interest)),LoanTerm))-(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)))/(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)-1);  //calculating the remaining balance of the loan
			double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);  //calculating the amount of interest paid each month


		result+=(""+Math.round(newterminmonths) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");
		newterminmonths = newterminmonths - 1;  //calculating the remaining months left on the loan
	}
		return result;
  }

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36602039
Actually this compiles - the one before still had one compilation error

/* Tim Hatch
 * sr_mf_003_cr5.java
 * September 26, 2011
 */

import java.awt.Dimension;
import java.awt.BorderLayout;           // Import and Provide Layout of Window
import java.awt.GridLayout;		// Import the Layout in Grid Format
import java.awt.event.ActionEvent;      // Import Action
import java.awt.event.ActionListener;   // Import Listener for Action
import javax.swing.JButton;             // Import Use of Buttons
import javax.swing.JFrame;		// Import Use of Frame
import javax.swing.JLabel;		// Import Use of Label
import javax.swing.JPanel;		// Import Use of Panel
import javax.swing.JTextField;		// Import Use of Text Field
import javax.swing.JTextArea;		// Import Use of Text Area
import javax.swing.JScrollPane;         // Import Scroll Pane
import javax.swing.JComboBox;           // Import JCombo Box
import java.text.DecimalFormat;         // Import Decimal Format to Eliminate Extra Places Past Decimal Point

//Creating the Mortgage Payment Class
public class sr_mf_03_cr5 extends JFrame
{
    DecimalFormat Dollar = new DecimalFormat("$000,000.00");
	//GUI elements to display current information
	private JLabel loanamountLabel = new JLabel("Initial Loan Amount");
	private JTextField LoanAmountTextField = new JTextField (20);

	private JLabel interestrateLabel = new JLabel("Interest Rate");

	String interestrate[] = {"Select Interest Rate","7 years at 5.35%","15 years at 5.5%","30 years at 5.75%"};

	private JComboBox combo = new JComboBox(interestrate);

	 private JTextArea result = new JTextArea(10, 20);
    JScrollPane scrollingResult = new JScrollPane(result);

	public sr_mf_03_cr5() {

		//building the panel for the buttons
		JPanel buttonPanel = new JPanel();

		//creating the "calculate" button
		 JButton btncalc = new JButton("Calculate");
		 btncalc.addActionListener(new ActionListener()
		 {
			public void actionPerformed(ActionEvent event)
			{
				onButtonCalc();
			}
		});
		//creating the "Reset" button
		JButton btnreset = new JButton("Reset");
		btnreset.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent event)
			{
				onButtonReset();
			}
		});
		//create the panel
		JPanel centerPanel = new JPanel();
		//set the layout
		centerPanel.setLayout(new GridLayout(3, 2,3,3));

		//add the components
		centerPanel.add(loanamountLabel);
		centerPanel.add(LoanAmountTextField);
		centerPanel.add(interestrateLabel);
		centerPanel.add(combo);

		centerPanel.add(btncalc);
		centerPanel.add(btnreset);

		setLayout(new BorderLayout());

        centerPanel.setPreferredSize(new Dimension(500,200));

        //adding to the frame
		        add(centerPanel, BorderLayout.CENTER);
		        add(scrollingResult, BorderLayout.SOUTH);

		        //setting the frame properties
		        pack();
		        setDefaultCloseOperation(EXIT_ON_CLOSE );
        //setResizable(false);
        setTitle("Mortgage Calculator");
        setVisible(true);
    }

    //calculate information
    public void onButtonCalc(){
		//getting the values
		double loanAmount=Double.parseDouble(LoanAmountTextField.getText());
		double interestrate=0.0;
		int loanterm=0;
 String str = (String)combo.getSelectedItem();
	if(str.equals("7 years at 5.35%"))
	{
            interestrate = 5.35 ;
            loanterm = 7 ;
	}
	else
	if(str.equals("15 years at 5.5%"))
	{
            interestrate = 5.5 ;
            loanterm = 15 ;
	}
	else
	if(str.equals("30 years at 5.75%"))
	{
            interestrate = 5.75 ;
            loanterm = 30 ;
	}

	//creating the new loan
	Loan loan = new Loan(loanAmount, interestrate, loanterm);

	//setting the result text
	        result.setText("Loan Amount = " + Dollar.format(loanAmount)
	    		+"\nInterest Rate = " + interestrate +"%"+"\nLength of Loan = "
	    		+ Math.round(loanterm* 12.0) + " months"+"\nMonthly Payment = "
	    		+ Dollar.format(loan.Calculatemonthlypayment())
	                + loan.LoanAmountRemaining());//calling the ComputeMonthlyPayment() method of loan class
    }

	//Information for Reset Button
	public void onButtonReset(){

		//resetting fields
		LoanAmountTextField.setText("");
			combo.setSelectedIndex(0);
		        result.setText("");
    }
    public static void main(String[] args){

		sr_mf_03_cr5 newloan = new sr_mf_03_cr5();   //creating an instance of the class
	}
}
//creating a class to store the loan data
class Loan {
	double LoanAmount; //original amount of the loan
	double Interest; //interest rate of the loan as a percent
	int LoanTerm;  //Term of the loan, expressed in years

 DecimalFormat Dollar = new DecimalFormat("000,000.00");

 public Loan(double LoanAmount, double Interst, int LoanTerm)
	{
		this.LoanAmount = LoanAmount;
		this.Interest = Interest;
		this.LoanTerm = LoanTerm;
	}

	//calculate the monthly payment
	public double Calculatemonthlypayment() {

		//setting the values before calculations are peformed
		double monthlyinterest = 0;  //ammount of interest paid each month
		double numberofpayments = 0; //number of payments remaining

		monthlyinterest = Calculatemonthlyinterest(Interest);
		numberofpayments = LoanTerm*12;
		return (LoanAmount * monthlyinterest) / (1.0-(Math.pow((1.0 + monthlyinterest),-numberofpayments)));
	}

	//caclulate the monthly interest
	public double Calculatemonthlyinterest(double Interest) {
		return Interest  / (100 * 12);
	}
	public String LoanAmountRemaining() {
		String result = "\n\n,onth\tloanbalance\tinterest paid\n";
		double terminmonths = LoanTerm * 12;  //converts the loan term from years to months
		double newterminmonths = terminmonths;	  //setting the variables up so that the number of months remaining on the loan (thus the remainder of monthly payments can be calculated

		//setting up while loop
		while (newterminmonths > 0) {

			double loanmonths = terminmonths-newterminmonths;  //calculating the amount of months left on the term
			double loanbalance = LoanAmount*((Math.pow((1 + Calculatemonthlyinterest(Interest)),LoanTerm))-(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)))/(Math.pow((1 + Calculatemonthlyinterest(Interest)),terminmonths)-1);  //calculating the remaining balance of the loan
			double monthlyinterest = loanbalance * Calculatemonthlyinterest(Interest);  //calculating the amount of interest paid each month


		result+=(""+Math.round(newterminmonths) + "\t" + Dollar.format(loanbalance) + "\t" + Dollar.format(monthlyinterest) + "\n");
		newterminmonths = newterminmonths - 1;  //calculating the remaining months left on the loan
	}
		return result;
  }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36602050
there is a good tradition in java - how to name variables, methods and classes in sense that
calsses should start with upper case, variables  and methods should not
It will be good idea to follow them
Also when you make it up ofg many words - capitalize each word in between
These rulles will help to eep case at least the same in all cases and not all over the place
0
 
LVL 2

Author Closing Comment

by:Winstink
ID: 36602465
thank you very much.  I thought I double checked everything.  I guess not.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
Suggested Courses

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

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

Join & Ask a Question