Solved

Missing a brace or something with Java

Posted on 2011-09-26
5
294 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
  • 3
5 Comments
 
LVL 37

Expert Comment

by:TommySzalapski
Comment Utility
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 500 total points
Comment Utility

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
Comment Utility
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
Comment Utility
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
Comment Utility
thank you very much.  I thought I double checked everything.  I guess not.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

This is an explanation of a simple data model to help parse a JSON feed
"Disruption" is the most feared word for C-level executives these days. They agonize over their industry being disturbed by another player - most likely by startups.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now