6 Replies - 4343 Views - Last Post: 18 March 2009 - 11:47 AM Rate Topic: -----

#1 skyscreamer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-March 09

multi-dimensional arrays?

Posted 17 March 2009 - 12:52 PM

Hello all.

I am working on a homework assignment that states:

Quote

* Write the program 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%
*
* Use an array for the mortgage data for the different loans. Display the mortgage payment
* amount followed by the loan balance and interest paid for each payment over the term of
* the loan. Allow the user to loop back and enter a new amount and make a new selection or
* quit. Please insert comments in the program to document the program.


I was wondering what would be better served for calculating this issue? Can (or even should) I use a multi-dimensional array to pull the year and the rate, or should I use two arrays to pull the information. Currently here is what I have:
	//establish the array
	double[][] ratesArray = {{7, 15, 30}, {5.35, 5.5, 5.75}};


		double amountPayment = ((loanAmount *(ratesArray[dropBoxCount][dropBoxCount] / 12)) 
				/ (1 - (Math.pow((1 + (ratesArray[dropBoxCount][dropBoxCount] / 12)), 
						((ratesArray[dropBoxCount][dropBoxCount] * 12) * -1)))));


What I'm trying do do in the equation is pull "just" the second value of the array. Should I try to set a variable just to represent that value in the equation (if so, how), or is there a way to pull it directly from the array?

Thank you for any help.

Is This A Good Question/Topic? 0
  • +

Replies To: multi-dimensional arrays?

#2 pbl  Icon User is online

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8027
  • View blog
  • Posts: 31,162
  • Joined: 06-March 08

Re: multi-dimensional arrays?

Posted 17 March 2009 - 05:23 PM

I am a lazy typer
I would use 2 different arrays:
- code easier to understand
- just one loop depth
- a lot of [][] avoided
- year[] is a year payment[] is a payment ratesArray[][] what are tne indexes ? Which one references years which one refrences payment ?
Was This Post Helpful? 1

#3 skyscreamer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-March 09

Re: multi-dimensional arrays?

Posted 18 March 2009 - 05:11 AM

Thank you so much for your help! It looks like 2 arrays is the way to go from my instructor as well. I can see how having a 2-dimensional array for two different types of values (rates and payments) could be quite confusing. Thanks so much for the advice!


View Postpbl, on 17 Mar, 2009 - 04:23 PM, said:

I am a lazy typer
I would use 2 different arrays:
- code easier to understand
- just one loop depth
- a lot of [][] avoided
- year[] is a year payment[] is a payment ratesArray[][] what are tne indexes ? Which one references years which one refrences payment ?

Was This Post Helpful? 0
  • +
  • -

#4 skyscreamer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-March 09

Re: multi-dimensional arrays?

Posted 18 March 2009 - 06:04 AM

I have one more question on this project. Currently it is returning a "-0.00" balance at the end. Is there a way to make it so that it is "0.00" instead?

import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.awt.event.*;


public class WK3IA_Howell extends JFrame{
	
	//Variables for the GUI labels, GUI fields, GUI buttons, and mathematical equations
	private JLabel loanAmountLabel; 		//variable for the loan amount label
	private JLabel resultsHeaders;			//variable for the headers of the results box
	private JTextField loanAmountField;		//variable for drop down box field
	private JComboBox dropDownBox;			//variable for drop down box
	private String resultsTab;				//variable for the aligning the results headers
	private JTextArea resultsText;			//variable for results text box
	private JScrollPane resultsPane;		//variable for the results pane
	private JButton calculatePayments; 		//variable for the calculate button
	private JButton resetFields;			//variable for the reset button
	private JButton closeProgram;			//variable for the close button
	private int dropBoxCount; 				//variable to keep track of the drop box selection
	private double interestPayment;			//variable for the interest payment
	private double loanAmount;				//variable for the loan amount
	private double amountPayment;			//variable for the amount of the payment
	
	//Create arrays and their values
	private int yearsArray[] = {7, 15, 30};
	private double ratesArray[] = {0.0535, 0.0550, 0.0575};

	//variable to establish the decimal format
	DecimalFormat decimalFormat = new DecimalFormat("0.00");
	
	
	public WK3IA_Howell (){
		super ("Dodge Howell's Mortgage Calculator");		//Create the label for the program
		createGUI();										//Call the method to create the interface
	}
	
	/******* begin Method to create the GUI Interface *******/
	public void createGUI(){
		setLocation(225, 175);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		
		//create first row
		JPanel firstRow = new JPanel();
		loanAmountLabel = new JLabel("Loan Amount:  $", JLabel.LEFT);
		loanAmountField = new JTextField(10);
		String[] dropDownBoxText = {"Select the Terms of the Loan", "7 Years at 5.35%",
				"15 Years at 5.35%","30 Years at 5.75%"};
		dropDownBox = new JComboBox(dropDownBoxText);
		firstRow.add(loanAmountLabel);
		firstRow.add(loanAmountField);
		firstRow.add(dropDownBox);
		
		//create second row
		JPanel secondRow = new JPanel(new BorderLayout());
		resultsTab = new String("							 ");
		resultsHeaders = new JLabel("Payment" + resultsTab + "Amount of Payment" + 
				resultsTab + "Interest Paid" +resultsTab + "Remaining Balance:");
		resultsText = new JTextArea(10, 53);
		resultsPane = new JScrollPane(resultsText);
		resultsPane.setPreferredSize(new Dimension(610, 200));
		secondRow.add(resultsHeaders,BorderLayout.NORTH);
		secondRow.add(resultsPane,BorderLayout.CENTER);
		
		//create third row
		JPanel thirdRow = new JPanel(new GridLayout(1, 3, 75, 1));
		calculatePayments = new JButton("Calculate Payments");
		resetFields = new JButton("Reset Form");
		closeProgram = new JButton("Close Program");
		thirdRow.add(calculatePayments);
		thirdRow.add(resetFields);
		thirdRow.add(closeProgram);
		
		//add Action Listeners
		calculatePayments.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				getResultValue();
			}
		});
		resetFields.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				clearFields();
			}
		});
		closeProgram.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				System.exit(0);
			}
		});
		
		//align the content pane
		getContentPane().add(firstRow, BorderLayout.NORTH);
		getContentPane().add(secondRow, BorderLayout.CENTER);
		getContentPane().add(thirdRow, BorderLayout.SOUTH);
		
		//Size the window
		pack();
	}
	
	/******* begin Method to process the Loan Rates *******/
	void getResultValue(){
		try{
			loanAmount = Double.parseDouble(loanAmountField.getText()); //retrieve the amount of the loan
		}
		catch(Exception e){
			JOptionPane.showMessageDialog(this, "Please enter a valid Loan Amount"); //send an error if the loan amount is invalid
			loanAmountField.requestFocus();
			return;
		}
	
		dropBoxCount = dropDownBox.getSelectedIndex() - 1; //Create an index in order to select the correct array value
		if (dropBoxCount < 0) {
			JOptionPane.showMessageDialog(this, "Please select a Loan Amount"); //send an error if no value is chosen
			dropDownBox.requestFocus();
			return;
		}
		//Calculate the monthly payment
		amountPayment = ((loanAmount *(ratesArray[dropBoxCount] / 12))
				/(1-(Math.pow((1+(ratesArray[dropBoxCount]/12)), ((yearsArray[dropBoxCount] * 12) * -1)))));
		
		//Calculate the interest and the remaining balance
		for(int index = 1; index <= (yearsArray[dropBoxCount] * 12); index++){
			interestPayment = loanAmount * (ratesArray[dropBoxCount] / 12);
			loanAmount -= (amountPayment - interestPayment);
			if (index == ratesArray[dropBoxCount] * 12 && loanAmount < 0){
			 loanAmount *= -1;
			}
			
			//Generate the text and place it in the defined decimal format
			resultsText.append(" " + index + "\t\t $" + decimalFormat.format(amountPayment)
			 + "\t\t" + decimalFormat.format(interestPayment) + "\t\t$"
			 + decimalFormat.format(loanAmount) + "\n");
		  }

		}
	// Method to clear all fields to be called upon by the reset fields button
	void clearFields(){
		loanAmountField.setText(null);
		dropDownBox.setSelectedIndex(0);
		resultsText.setText("");
	}
	//Main method
	public static void main(String[] args){
		new WK3IA_Howell().setVisible(true);
	}
}
//End of Program

Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 4888
  • View blog
  • Posts: 11,282
  • Joined: 16-October 07

Re: multi-dimensional arrays?

Posted 18 March 2009 - 09:21 AM

View Postskyscreamer, on 18 Mar, 2009 - 06:11 AM, said:

It looks like 2 arrays is the way to go from my instructor as well.


Ack, your instructor is wrong. Parallel arrays are bad; always.

In just the tiny snipped you've offered, you've already generated confusion:
double amountPayment = ((loanAmount *(ratesArray[dropBoxCount][dropBoxCount] / 12)) 
				/ (1 - (Math.pow((1 + (ratesArray[dropBoxCount][dropBoxCount] / 12)), 
						((ratesArray[dropBoxCount][dropBoxCount] * 12) * -1)))));

// are you looking for years or rate? either way, [x][x] is wrong
// [0][x] is years, [1][x] is rate
//dropBoxCount=2;
//ratesArray[dropBoxCount][dropBoxCount]== OutOfRange



Let's just make a little class to hold our data:
class RateItem {
	public final int years;
	public final double rate;
	public RateItem(int years, double rate) {
		this.years = years;
		this.rate = rate;
	}
	public String toString() { 
		return years + " years at " + rate + "%";
	}
}

RateItem [] rates = { new RateItem(7, 5.35), new RateItem(15, 5.5),	new RateItem(30, 5.75)};
int dropBoxCount=2;
double rate = rates[dropBoxCount].rate;



Note, your amountPayment formula looks very wrong. Also, consider giving the method to RateItem for simpler code.

And your rate actually isn't a percentage; you'll want to do a rate/100 at some point.

Hope this helps.

This post has been edited by baavgai: 18 March 2009 - 09:21 AM

Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 4888
  • View blog
  • Posts: 11,282
  • Joined: 16-October 07

Re: multi-dimensional arrays?

Posted 18 March 2009 - 10:47 AM

View Postskyscreamer, on 18 Mar, 2009 - 07:04 AM, said:

Currently it is returning a "-0.00" balance at the end. Is there a way to make it so that it is "0.00" instead?


First, the program is well written, good job. You have minor bug were you "setVisible(true);" on your init, get rid of that.

The issue that you're running into, and you should be aware of anyway, is floating drift and format masks.

Doing a little test, I added this line after your regular print.
resultsText.append(": " + loanAmount + "\n");



Here are some of the results.
83		 $176.52		1.56		$175.74
: 175.73707423917787
 84		 $176.52		0.78		$-0.00
: -3.3497826734674163E-10



So, you're getting a negative because you have a negative value. A really tiny one, that rounds to nothing.

Also, notice the mess that format is shielding you from. There is a chance that that the quirks of floating point will throw you off by a penny here and there. The safest way to do this is to avoid double entirely. Work in ints of pennies.

As a patch, since you should never have a negative value in that column, you could just Math.abs it.

This post has been edited by baavgai: 18 March 2009 - 10:48 AM

Was This Post Helpful? 0
  • +
  • -

#7 skyscreamer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-March 09

Re: multi-dimensional arrays?

Posted 18 March 2009 - 11:47 AM

View Postbaavgai, on 18 Mar, 2009 - 09:47 AM, said:

First, the program is well written, good job. You have minor bug were you "setVisible(true);" on your init, get rid of that.

The issue that you're running into, and you should be aware of anyway, is floating drift and format masks.

So, you're getting a negative because you have a negative value. A really tiny one, that rounds to nothing.

Also, notice the mess that format is shielding you from. There is a chance that that the quirks of floating point will throw you off by a penny here and there. The safest way to do this is to avoid double entirely. Work in ints of pennies.

As a patch, since you should never have a negative value in that column, you could just Math.abs it.


Thank you very much for the compliment and the help! I see what you're saying about the negative value and about using Math.abs in order to create a patch of types. It appears to have solved the issue, but I think I'm going to work on it a bit more to see if I can get more accurate results by avoiding doubles :) Thank you so much!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1