pgmtkl
asked on
converting string to percentage rate
I am coding a gui java program that takes users input and calculates mortgage amount. The program runs ok but i realized the rate was converting to Double.parseDouble which was causign the mortgage amounts to be way off the amount it should of been. I have to convert the rate to a percentage but when i changed the below section to percentFormat.parse(rate) it did not work. I receive error from compiler- MortgageGui1.java:58: cannot find symbol. How do you convert a string to a percentage rate?
rate = JOptionPane.showInputDialo g(null,"Pl ease enter annual finance rate:", " ", JOptionPane.QUESTION_MESSA GE);
rateValue = percentFormat.parse(rate);
rate = JOptionPane.showInputDialo
rateValue = percentFormat.parse(rate);
Hi pgmtkl,
Be sure to use the following packages :
import javax.swing.*;
import java.text.*;
Be sure to use the following packages :
import javax.swing.*;
import java.text.*;
ASKER
Hi. I had java.text.decimal format imported but i did change that to java.text.* and it was ok. However, the calculation is still off. I have posted the code below. The program compiles and runs, but something is not right, I beleive it is with the percentage rate. Am i missing something?
import javax.swing.*;
import java.text.*;//DecimalForma t;
import java.math.*;
import java.lang.*;
public class MortgageGui1
{
//public static void main(String[] args)throws Exception
public static void main(String[] args) throws Exception
{
int val = 0;
String amount;
String rate;
String term;
int response = 0;
boolean valid = true;
double termValue;
double amountValue;
double rateValue;
do{
// The showInoutDialog is a method of JOptionPane and its return value is a string.
// Since the return value is a string, it is necessary that "grade" should be of a string
// datatype too.
amount = JOptionPane.showInputDialo g(null,"Pl ease enter amount to be financed:", " ", JOptionPane.QUESTION_MESSA GE);
amountValue = Double.parseDouble(amount) ;
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
val = Integer.parseInt(amount);
if (val < 0){
JOptionPane.showMessageDia log(null, "Amount cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 2000000) {
JOptionPane.showMessageDia log(null, "Amount cannot exceed $2,000,000", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
rate = JOptionPane.showInputDialo g(null,"Pl ease enter annual finance rate:", " ", JOptionPane.QUESTION_MESSA GE);
//rateValue = percentFormat.parse(rate);
rateValue = Double.parseDouble(rate);
try {
val = Integer.parseInt(rate);
if (val <0){
JOptionPane.showMessageDia log(null, "Annual Finance rate cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 14) {
JOptionPane.showMessageDia log(null, "Annual Finance Rate cannot exceed 14%", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
term = JOptionPane.showInputDialo g(null,"Pl ease enter months/term of loan:", " ", JOptionPane.QUESTION_MESSA GE);
termValue = Double.parseDouble(term);
try {
val = Integer.parseInt(term);
if (val <0){
JOptionPane.showMessageDia log(null, "Months/Term cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 480) {
JOptionPane.showMessageDia log(null, "Months/Term cannot exceed 480 months", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
//calculation of mortgage
//double rate -interest is entered by user above
//double amount- loan amount is entered by user above
//double intValue;
//intValue = rate/12; //*Monthy interest to be used in calculation
double J=rateValue/12;
//term - term of loan is entered by user above
DecimalFormat df = new DecimalFormat("$#,###.00") ;// to display amount in correct format
//double mortgage = (Math.pow((1 + J), term) -1) / (J * Math.pow((1 + J), term));
//double payment = amount/ mortgage; //*Rate Calculation
double mortgage = (Math.pow((1 + J), termValue) - 1)
/ (J * Math.pow((1 + J), termValue));
double payment = amountValue / mortgage; //*Rate Calculation
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
if (val > 0) {
JOptionPane.showMessageDia log(null,e ndAmount," Informatio n",JOption Pane.INFOR MATION_MES SAGE);
// JOptionPane.showMessageDia log(null," Your monthly mortgage payment is " + payment,"Information",JOpt ionPane.IN FORMATION_ MESSAGE);
response = JOptionPane.showConfirmDia log(null," Would you like to perform another calculation?",
"Try Again?",JOptionPane.YES_NO _OPTION);
}
}
while (response == 0);
}
}
// End of program
import javax.swing.*;
import java.text.*;//DecimalForma
import java.math.*;
import java.lang.*;
public class MortgageGui1
{
//public static void main(String[] args)throws Exception
public static void main(String[] args) throws Exception
{
int val = 0;
String amount;
String rate;
String term;
int response = 0;
boolean valid = true;
double termValue;
double amountValue;
double rateValue;
do{
// The showInoutDialog is a method of JOptionPane and its return value is a string.
// Since the return value is a string, it is necessary that "grade" should be of a string
// datatype too.
amount = JOptionPane.showInputDialo
amountValue = Double.parseDouble(amount)
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
val = Integer.parseInt(amount);
if (val < 0){
JOptionPane.showMessageDia
continue;
}
else if (val > 2000000) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
rate = JOptionPane.showInputDialo
//rateValue = percentFormat.parse(rate);
rateValue = Double.parseDouble(rate);
try {
val = Integer.parseInt(rate);
if (val <0){
JOptionPane.showMessageDia
continue;
}
else if (val > 14) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
term = JOptionPane.showInputDialo
termValue = Double.parseDouble(term);
try {
val = Integer.parseInt(term);
if (val <0){
JOptionPane.showMessageDia
continue;
}
else if (val > 480) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
//calculation of mortgage
//double rate -interest is entered by user above
//double amount- loan amount is entered by user above
//double intValue;
//intValue = rate/12; //*Monthy interest to be used in calculation
double J=rateValue/12;
//term - term of loan is entered by user above
DecimalFormat df = new DecimalFormat("$#,###.00")
//double mortgage = (Math.pow((1 + J), term) -1) / (J * Math.pow((1 + J), term));
//double payment = amount/ mortgage; //*Rate Calculation
double mortgage = (Math.pow((1 + J), termValue) - 1)
/ (J * Math.pow((1 + J), termValue));
double payment = amountValue / mortgage; //*Rate Calculation
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
if (val > 0) {
JOptionPane.showMessageDia
// JOptionPane.showMessageDia
response = JOptionPane.showConfirmDia
"Try Again?",JOptionPane.YES_NO
}
}
while (response == 0);
}
}
// End of program
What formula is to be used (in plain maths)? Perhaps this is wrong:
>> double mortgage = (Math.pow((1 + J), termValue) - 1) / (J * Math.pow((1 + J), termValue));
>> double payment = amountValue / mortgage;
>> double mortgage = (Math.pow((1 + J), termValue) - 1) / (J * Math.pow((1 + J), termValue));
>> double payment = amountValue / mortgage;
>>
rateValue = Double.parseDouble(rate);
try {
val = Integer.parseInt(rate);
>>
Don't try to parse double values as integer.
remove the following lines :
val = Integer.parseInt(rate);
...
val = Integer.parseInt(term);
and use double constant to compare
if (rateValue > 14.0)
...
rateValue = Double.parseDouble(rate);
try {
val = Integer.parseInt(rate);
>>
Don't try to parse double values as integer.
remove the following lines :
val = Integer.parseInt(rate);
...
val = Integer.parseInt(term);
and use double constant to compare
if (rateValue > 14.0)
...
And
val = Integer.parseInt(amount);
val = Integer.parseInt(amount);
Hi,
try this example::::
/*
* InputVerificationDemo.java is a 1.4 example that
* requires no other files.
*/
import java.util.Set;
import java.util.HashSet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.beans.PropertyChangeL istener;
import java.beans.PropertyChangeE vent;
import java.text.*;
/**
* InputVerificationDemo.java is a 1.4 example that
* requires no other files.
*
* Yet another mortgage calculator.
* However, instead of using a formatted text field,
* as shown in FormattedTextFieldDemo, this example
* uses input verification to validate user input.
*/
public class InputVerificationDemo extends JPanel {
//Default values
private static double DEFAULT_AMOUNT = 100000;
private static double DEFAULT_RATE = 7.5; //7.5%
private static int DEFAULT_PERIOD = 30;
//Labels to identify the text fields
private JLabel amountLabel;
private JLabel rateLabel;
private JLabel numPeriodsLabel;
private JLabel paymentLabel;
//Strings for the labels
private static String amountString = "Loan Amount (10,000-10,000,000): ";
private static String rateString = "APR (>= 0%): ";
private static String numPeriodsString = "Years (1-40): ";
private static String paymentString = "Monthly Payment: ";
//Text fields for data entry
private JTextField amountField;
private JTextField rateField;
private JTextField numPeriodsField;
private JTextField paymentField;
//Formats to format and parse numbers
private NumberFormat moneyFormat;
private NumberFormat percentFormat;
private DecimalFormat decimalFormat;
private DecimalFormat paymentFormat;
private MyVerifier verifier = new MyVerifier();
public InputVerificationDemo() {
super(new BorderLayout());
setUpFormats();
double payment = computePayment(DEFAULT_AMO UNT,
DEFAULT_RATE,
DEFAULT_PERIOD);
//Create the labels.
amountLabel = new JLabel(amountString);
rateLabel = new JLabel(rateString);
numPeriodsLabel = new JLabel(numPeriodsString);
paymentLabel = new JLabel(paymentString);
//Create the text fields and set them up.
amountField = new JTextField(moneyFormat.for mat(DEFAUL T_AMOUNT), 10);
amountField.setInputVerifi er(verifie r);
rateField = new JTextField(percentFormat.f ormat(DEFA ULT_RATE), 10);
rateField.setInputVerifier (verifier) ;
numPeriodsField = new JTextField(decimalFormat.f ormat(DEFA ULT_PERIOD ), 10);
numPeriodsField.setInputVe rifier(ver ifier);
paymentField = new JTextField(paymentFormat.f ormat(paym ent), 10);
paymentField.setInputVerif ier(verifi er);
paymentField.setEditable(f alse);
//Remove this component from the focus cycle.
paymentField.setFocusable( false);
paymentField.setForeground (Color.red );
//Register an action listener to handle Return.
amountField.addActionListe ner(verifi er);
rateField.addActionListene r(verifier );
numPeriodsField.addActionL istener(ve rifier);
//Tell accessibility tools about label/textfield pairs.
amountLabel.setLabelFor(am ountField) ;
rateLabel.setLabelFor(rate Field);
numPeriodsLabel.setLabelFo r(numPerio dsField);
paymentLabel.setLabelFor(p aymentFiel d);
//Lay out the labels in a panel.
JPanel labelPane = new JPanel(new GridLayout(0,1));
labelPane.add(amountLabel) ;
labelPane.add(rateLabel);
labelPane.add(numPeriodsLa bel);
labelPane.add(paymentLabel );
//Layout the text fields in a panel.
JPanel fieldPane = new JPanel(new GridLayout(0,1));
fieldPane.add(amountField) ;
fieldPane.add(rateField);
fieldPane.add(numPeriodsFi eld);
fieldPane.add(paymentField );
//Put the panels in this panel, labels on left,
//text fields on right.
setBorder(BorderFactory.cr eateEmptyB order(20, 20, 20, 20));
add(labelPane, BorderLayout.CENTER);
add(fieldPane, BorderLayout.LINE_END);
}
class MyVerifier extends InputVerifier
implements ActionListener {
double MIN_AMOUNT = 10000.0;
double MAX_AMOUNT = 10000000.0;
double MIN_RATE = 0.0;
int MIN_PERIOD = 1;
int MAX_PERIOD = 40;
public boolean shouldYieldFocus(JComponen t input) {
boolean inputOK = verify(input);
makeItPretty(input);
updatePayment();
if (inputOK) {
return true;
} else {
Toolkit.getDefaultToolkit( ).beep();
return false;
}
}
protected void updatePayment() {
double amount = DEFAULT_AMOUNT;
double rate = DEFAULT_RATE;
int numPeriods = DEFAULT_PERIOD;
double payment = 0.0;
//Parse the values.
try {
amount = moneyFormat.parse(amountFi eld.getTex t()).
doubleValue();
} catch (ParseException pe) {}
try {
rate = percentFormat.parse(rateFi eld.getTex t()).
doubleValue();
} catch (ParseException pe) {}
try {
numPeriods = decimalFormat.parse(numPer iodsField. getText()) .
intValue();
} catch (ParseException pe) {}
//Calculate the result and update the GUI.
payment = computePayment(amount, rate, numPeriods);
paymentField.setText(payme ntFormat.f ormat(paym ent));
}
//This method checks input, but should cause no side effects.
public boolean verify(JComponent input) {
return checkField(input, false);
}
protected void makeItPretty(JComponent input) {
checkField(input, true);
}
protected boolean checkField(JComponent input, boolean changeIt) {
if (input == amountField) {
return checkAmountField(changeIt) ;
} else if (input == rateField) {
return checkRateField(changeIt);
} else if (input == numPeriodsField) {
return checkNumPeriodsField(chang eIt);
} else {
return true; //shouldn't happen
}
}
//Checks that the amount field is valid. If it is valid,
//it returns true; otherwise, returns false. If the
//change argument is true, this method reigns in the
//value if necessary and (even if not) sets it to the
//parsed number so that it looks good -- no letters,
//for example.
protected boolean checkAmountField(boolean change) {
boolean wasValid = true;
double amount = DEFAULT_AMOUNT;
//Parse the value.
try {
amount = moneyFormat.parse(amountFi eld.getTex t()).
doubleValue();
} catch (ParseException pe) {
wasValid = false;
}
//Value was invalid.
if ((amount < MIN_AMOUNT) || (amount > MAX_AMOUNT)) {
wasValid = false;
if (change) {
if (amount < MIN_AMOUNT) {
amount = MIN_AMOUNT;
} else { // amount is greater than MAX_AMOUNT
amount = MAX_AMOUNT;
}
}
}
//Whether value was valid or not, format it nicely.
if (change) {
amountField.setText(moneyF ormat.form at(amount) );
amountField.selectAll();
}
return wasValid;
}
//Checks that the rate field is valid. If it is valid,
//it returns true; otherwise, returns false. If the
//change argument is true, this method reigns in the
//value if necessary and (even if not) sets it to the
//parsed number so that it looks good -- no letters,
//for example.
protected boolean checkRateField(boolean change) {
boolean wasValid = true;
double rate = DEFAULT_RATE;
//Parse the value.
try {
rate = percentFormat.parse(rateFi eld.getTex t()).
doubleValue();
} catch (ParseException pe) {
wasValid = false;
}
//Value was invalid.
if (rate < MIN_RATE) {
wasValid = false;
if (change) {
rate = MIN_RATE;
}
}
//Whether value was valid or not, format it nicely.
if (change) {
rateField.setText(percentF ormat.form at(rate));
rateField.selectAll();
}
return wasValid;
}
//Checks that the numPeriods field is valid. If it is valid,
//it returns true; otherwise, returns false. If the
//change argument is true, this method reigns in the
//value if necessary and (even if not) sets it to the
//parsed number so that it looks good -- no letters,
//for example.
protected boolean checkNumPeriodsField(boole an change) {
boolean wasValid = true;
int numPeriods = DEFAULT_PERIOD;
//Parse the value.
try {
numPeriods = decimalFormat.parse(numPer iodsField. getText()) .
intValue();
} catch (ParseException pe) {
wasValid = false;
}
//Value was invalid.
if ((numPeriods < MIN_PERIOD) || (numPeriods > MAX_PERIOD)) {
wasValid = false;
if (change) {
if (numPeriods < MIN_PERIOD) {
numPeriods = MIN_PERIOD;
} else { // numPeriods is greater than MAX_PERIOD
numPeriods = MAX_PERIOD;
}
}
}
//Whether value was valid or not, format it nicely.
if (change) {
numPeriodsField.setText(de cimalForma t.format(n umPeriods) );
numPeriodsField.selectAll( );
}
return wasValid;
}
public void actionPerformed(ActionEven t e) {
JTextField source = (JTextField)e.getSource();
shouldYieldFocus(source); //ignore return value
source.selectAll();
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFe elDecorate d(true);
//Create and set up the window.
JFrame frame = new JFrame("InputVerificationD emo");
frame.setDefaultCloseOpera tion(JFram e.EXIT_ON_ CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new InputVerificationDemo();
newContentPane.setOpaque(t rue); //content panes must be opaque
frame.setContentPane(newCo ntentPane) ;
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities .invokeLat er(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
//Compute the monthly payment based on the loan amount,
//APR, and length of loan.
double computePayment(double loanAmt, double rate, int numPeriods) {
double I, partial1, denominator, answer;
numPeriods *= 12; //get number of months
if (rate > 0.01) {
I = rate / 100.0 / 12.0; //get monthly rate from annual
partial1 = Math.pow((1 + I), (0.0 - numPeriods));
denominator = (1 - partial1) / I;
} else { //rate ~= 0
denominator = numPeriods;
}
answer = (-1 * loanAmt) / denominator;
return answer;
}
//Create and set up number formats. These objects are used
//for both parsing input and formatting output.
private void setUpFormats() {
moneyFormat = (NumberFormat)NumberFormat .getNumber Instance() ;
percentFormat = NumberFormat.getNumberInst ance();
percentFormat.setMinimumFr actionDigi ts(3);
decimalFormat = (DecimalFormat)NumberForma t.getNumbe rInstance( );
decimalFormat.setParseInte gerOnly(tr ue);
paymentFormat = (DecimalFormat)NumberForma t.getNumbe rInstance( );
paymentFormat.setMaximumFr actionDigi ts(2);
paymentFormat.setNegativeP refix("(") ;
paymentFormat.setNegativeS uffix(")") ;
}
}
R.K
try this example::::
/*
* InputVerificationDemo.java
* requires no other files.
*/
import java.util.Set;
import java.util.HashSet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.beans.PropertyChangeL
import java.beans.PropertyChangeE
import java.text.*;
/**
* InputVerificationDemo.java
* requires no other files.
*
* Yet another mortgage calculator.
* However, instead of using a formatted text field,
* as shown in FormattedTextFieldDemo, this example
* uses input verification to validate user input.
*/
public class InputVerificationDemo extends JPanel {
//Default values
private static double DEFAULT_AMOUNT = 100000;
private static double DEFAULT_RATE = 7.5; //7.5%
private static int DEFAULT_PERIOD = 30;
//Labels to identify the text fields
private JLabel amountLabel;
private JLabel rateLabel;
private JLabel numPeriodsLabel;
private JLabel paymentLabel;
//Strings for the labels
private static String amountString = "Loan Amount (10,000-10,000,000): ";
private static String rateString = "APR (>= 0%): ";
private static String numPeriodsString = "Years (1-40): ";
private static String paymentString = "Monthly Payment: ";
//Text fields for data entry
private JTextField amountField;
private JTextField rateField;
private JTextField numPeriodsField;
private JTextField paymentField;
//Formats to format and parse numbers
private NumberFormat moneyFormat;
private NumberFormat percentFormat;
private DecimalFormat decimalFormat;
private DecimalFormat paymentFormat;
private MyVerifier verifier = new MyVerifier();
public InputVerificationDemo() {
super(new BorderLayout());
setUpFormats();
double payment = computePayment(DEFAULT_AMO
DEFAULT_RATE,
DEFAULT_PERIOD);
//Create the labels.
amountLabel = new JLabel(amountString);
rateLabel = new JLabel(rateString);
numPeriodsLabel = new JLabel(numPeriodsString);
paymentLabel = new JLabel(paymentString);
//Create the text fields and set them up.
amountField = new JTextField(moneyFormat.for
amountField.setInputVerifi
rateField = new JTextField(percentFormat.f
rateField.setInputVerifier
numPeriodsField = new JTextField(decimalFormat.f
numPeriodsField.setInputVe
paymentField = new JTextField(paymentFormat.f
paymentField.setInputVerif
paymentField.setEditable(f
//Remove this component from the focus cycle.
paymentField.setFocusable(
paymentField.setForeground
//Register an action listener to handle Return.
amountField.addActionListe
rateField.addActionListene
numPeriodsField.addActionL
//Tell accessibility tools about label/textfield pairs.
amountLabel.setLabelFor(am
rateLabel.setLabelFor(rate
numPeriodsLabel.setLabelFo
paymentLabel.setLabelFor(p
//Lay out the labels in a panel.
JPanel labelPane = new JPanel(new GridLayout(0,1));
labelPane.add(amountLabel)
labelPane.add(rateLabel);
labelPane.add(numPeriodsLa
labelPane.add(paymentLabel
//Layout the text fields in a panel.
JPanel fieldPane = new JPanel(new GridLayout(0,1));
fieldPane.add(amountField)
fieldPane.add(rateField);
fieldPane.add(numPeriodsFi
fieldPane.add(paymentField
//Put the panels in this panel, labels on left,
//text fields on right.
setBorder(BorderFactory.cr
add(labelPane, BorderLayout.CENTER);
add(fieldPane, BorderLayout.LINE_END);
}
class MyVerifier extends InputVerifier
implements ActionListener {
double MIN_AMOUNT = 10000.0;
double MAX_AMOUNT = 10000000.0;
double MIN_RATE = 0.0;
int MIN_PERIOD = 1;
int MAX_PERIOD = 40;
public boolean shouldYieldFocus(JComponen
boolean inputOK = verify(input);
makeItPretty(input);
updatePayment();
if (inputOK) {
return true;
} else {
Toolkit.getDefaultToolkit(
return false;
}
}
protected void updatePayment() {
double amount = DEFAULT_AMOUNT;
double rate = DEFAULT_RATE;
int numPeriods = DEFAULT_PERIOD;
double payment = 0.0;
//Parse the values.
try {
amount = moneyFormat.parse(amountFi
doubleValue();
} catch (ParseException pe) {}
try {
rate = percentFormat.parse(rateFi
doubleValue();
} catch (ParseException pe) {}
try {
numPeriods = decimalFormat.parse(numPer
intValue();
} catch (ParseException pe) {}
//Calculate the result and update the GUI.
payment = computePayment(amount, rate, numPeriods);
paymentField.setText(payme
}
//This method checks input, but should cause no side effects.
public boolean verify(JComponent input) {
return checkField(input, false);
}
protected void makeItPretty(JComponent input) {
checkField(input, true);
}
protected boolean checkField(JComponent input, boolean changeIt) {
if (input == amountField) {
return checkAmountField(changeIt)
} else if (input == rateField) {
return checkRateField(changeIt);
} else if (input == numPeriodsField) {
return checkNumPeriodsField(chang
} else {
return true; //shouldn't happen
}
}
//Checks that the amount field is valid. If it is valid,
//it returns true; otherwise, returns false. If the
//change argument is true, this method reigns in the
//value if necessary and (even if not) sets it to the
//parsed number so that it looks good -- no letters,
//for example.
protected boolean checkAmountField(boolean change) {
boolean wasValid = true;
double amount = DEFAULT_AMOUNT;
//Parse the value.
try {
amount = moneyFormat.parse(amountFi
doubleValue();
} catch (ParseException pe) {
wasValid = false;
}
//Value was invalid.
if ((amount < MIN_AMOUNT) || (amount > MAX_AMOUNT)) {
wasValid = false;
if (change) {
if (amount < MIN_AMOUNT) {
amount = MIN_AMOUNT;
} else { // amount is greater than MAX_AMOUNT
amount = MAX_AMOUNT;
}
}
}
//Whether value was valid or not, format it nicely.
if (change) {
amountField.setText(moneyF
amountField.selectAll();
}
return wasValid;
}
//Checks that the rate field is valid. If it is valid,
//it returns true; otherwise, returns false. If the
//change argument is true, this method reigns in the
//value if necessary and (even if not) sets it to the
//parsed number so that it looks good -- no letters,
//for example.
protected boolean checkRateField(boolean change) {
boolean wasValid = true;
double rate = DEFAULT_RATE;
//Parse the value.
try {
rate = percentFormat.parse(rateFi
doubleValue();
} catch (ParseException pe) {
wasValid = false;
}
//Value was invalid.
if (rate < MIN_RATE) {
wasValid = false;
if (change) {
rate = MIN_RATE;
}
}
//Whether value was valid or not, format it nicely.
if (change) {
rateField.setText(percentF
rateField.selectAll();
}
return wasValid;
}
//Checks that the numPeriods field is valid. If it is valid,
//it returns true; otherwise, returns false. If the
//change argument is true, this method reigns in the
//value if necessary and (even if not) sets it to the
//parsed number so that it looks good -- no letters,
//for example.
protected boolean checkNumPeriodsField(boole
boolean wasValid = true;
int numPeriods = DEFAULT_PERIOD;
//Parse the value.
try {
numPeriods = decimalFormat.parse(numPer
intValue();
} catch (ParseException pe) {
wasValid = false;
}
//Value was invalid.
if ((numPeriods < MIN_PERIOD) || (numPeriods > MAX_PERIOD)) {
wasValid = false;
if (change) {
if (numPeriods < MIN_PERIOD) {
numPeriods = MIN_PERIOD;
} else { // numPeriods is greater than MAX_PERIOD
numPeriods = MAX_PERIOD;
}
}
}
//Whether value was valid or not, format it nicely.
if (change) {
numPeriodsField.setText(de
numPeriodsField.selectAll(
}
return wasValid;
}
public void actionPerformed(ActionEven
JTextField source = (JTextField)e.getSource();
shouldYieldFocus(source); //ignore return value
source.selectAll();
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFe
//Create and set up the window.
JFrame frame = new JFrame("InputVerificationD
frame.setDefaultCloseOpera
//Create and set up the content pane.
JComponent newContentPane = new InputVerificationDemo();
newContentPane.setOpaque(t
frame.setContentPane(newCo
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities
public void run() {
createAndShowGUI();
}
});
}
//Compute the monthly payment based on the loan amount,
//APR, and length of loan.
double computePayment(double loanAmt, double rate, int numPeriods) {
double I, partial1, denominator, answer;
numPeriods *= 12; //get number of months
if (rate > 0.01) {
I = rate / 100.0 / 12.0; //get monthly rate from annual
partial1 = Math.pow((1 + I), (0.0 - numPeriods));
denominator = (1 - partial1) / I;
} else { //rate ~= 0
denominator = numPeriods;
}
answer = (-1 * loanAmt) / denominator;
return answer;
}
//Create and set up number formats. These objects are used
//for both parsing input and formatting output.
private void setUpFormats() {
moneyFormat = (NumberFormat)NumberFormat
percentFormat = NumberFormat.getNumberInst
percentFormat.setMinimumFr
decimalFormat = (DecimalFormat)NumberForma
decimalFormat.setParseInte
paymentFormat = (DecimalFormat)NumberForma
paymentFormat.setMaximumFr
paymentFormat.setNegativeP
paymentFormat.setNegativeS
}
}
R.K
ASKER
webstorm: i tried this but the calculation is still off. I know the formula works because i used the exact formula in a program that did not have the gui interface. When i removed the try { val=interger lines the program continuily loops. Are there other statements missing that i overlooked???
this is the updated program which just loops:
import javax.swing.*;
import java.text.*; //DecimalFormat;
import java.math.*;
import java.lang.*;
public class MortgageGui1
{
//public static void main(String[] args)throws Exception
public static void main(String[] args) throws Exception
{
int val = 0;
String amount;
String rate;
String term;
int response = 0;
boolean valid = true;
double termValue;
double amountValue;
double rateValue;
do{
// The showInoutDialog is a method of JOptionPane and its return value is a string.
// Since the return value is a string, it is necessary that "grade" should be of a string
// datatype too.
amount = JOptionPane.showInputDialo g(null,"Pl ease enter amount to be financed:", " ", JOptionPane.QUESTION_MESSA GE);
amountValue = Double.parseDouble(amount) ;
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
// val = Integer.parseInt(amount);
if (val < 0){
JOptionPane.showMessageDia log(null, "Amount cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 2000000) {
JOptionPane.showMessageDia log(null, "Amount cannot exceed $2,000,000", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
rate = JOptionPane.showInputDialo g(null,"Pl ease enter finance rate:", " ", JOptionPane.QUESTION_MESSA GE);
rateValue = Double.parseDouble(rate);
try {
// val = Integer.parseInt(rate);
if (val <0){
JOptionPane.showMessageDia log(null, "Finance rate cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 14.0) {
JOptionPane.showMessageDia log(null, "Finance Rate cannot exceed 14%", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
term = JOptionPane.showInputDialo g(null,"Pl ease enter term:", " ", JOptionPane.QUESTION_MESSA GE);
termValue = Double.parseDouble(term);
try {
// val = Integer.parseInt(term);
if (val <0){
JOptionPane.showMessageDia log(null, "Term cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 480) {
JOptionPane.showMessageDia log(null, "Finance Rate cannot exceed 480 months", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
//calculation of mortgage
//double rate -interest is entered by user above
//double amount- loan amount is entered by user above
//double intValue;
//intValue = rate/12; //*Monthy interest to be used in calculation
double J=rateValue/12;
//term - term of loan is entered by user above
DecimalFormat df = new DecimalFormat("$#,###.00") ;// to display amount in correct format
//double mortgage = (Math.pow((1 + J), term) -1) / (J * Math.pow((1 + J), term));
//double payment = amount/ mortgage; //*Rate Calculation
double mortgage = (Math.pow((1 + J), termValue) - 1)
/ (J * Math.pow((1 + J), termValue));
double payment = amountValue / mortgage; //*Rate Calculation
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
if (val > 0) {
JOptionPane.showMessageDia log(null,e ndAmount," Informatio n",JOption Pane.INFOR MATION_MES SAGE);
// JOptionPane.showMessageDia log(null," Your monthly mortgage payment is " + payment,"Information",JOpt ionPane.IN FORMATION_ MESSAGE);
response = JOptionPane.showConfirmDia log(null," Would you like to perform another calculation?",
"Try Again?",JOptionPane.YES_NO _OPTION);
}
}
while (response == 0);
}
}
// End of program
this is the updated program which just loops:
import javax.swing.*;
import java.text.*; //DecimalFormat;
import java.math.*;
import java.lang.*;
public class MortgageGui1
{
//public static void main(String[] args)throws Exception
public static void main(String[] args) throws Exception
{
int val = 0;
String amount;
String rate;
String term;
int response = 0;
boolean valid = true;
double termValue;
double amountValue;
double rateValue;
do{
// The showInoutDialog is a method of JOptionPane and its return value is a string.
// Since the return value is a string, it is necessary that "grade" should be of a string
// datatype too.
amount = JOptionPane.showInputDialo
amountValue = Double.parseDouble(amount)
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
// val = Integer.parseInt(amount);
if (val < 0){
JOptionPane.showMessageDia
continue;
}
else if (val > 2000000) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
rate = JOptionPane.showInputDialo
rateValue = Double.parseDouble(rate);
try {
// val = Integer.parseInt(rate);
if (val <0){
JOptionPane.showMessageDia
continue;
}
else if (val > 14.0) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
term = JOptionPane.showInputDialo
termValue = Double.parseDouble(term);
try {
// val = Integer.parseInt(term);
if (val <0){
JOptionPane.showMessageDia
continue;
}
else if (val > 480) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
//calculation of mortgage
//double rate -interest is entered by user above
//double amount- loan amount is entered by user above
//double intValue;
//intValue = rate/12; //*Monthy interest to be used in calculation
double J=rateValue/12;
//term - term of loan is entered by user above
DecimalFormat df = new DecimalFormat("$#,###.00")
//double mortgage = (Math.pow((1 + J), term) -1) / (J * Math.pow((1 + J), term));
//double payment = amount/ mortgage; //*Rate Calculation
double mortgage = (Math.pow((1 + J), termValue) - 1)
/ (J * Math.pow((1 + J), termValue));
double payment = amountValue / mortgage; //*Rate Calculation
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
if (val > 0) {
JOptionPane.showMessageDia
// JOptionPane.showMessageDia
response = JOptionPane.showConfirmDia
"Try Again?",JOptionPane.YES_NO
}
}
while (response == 0);
}
}
// End of program
What is the input you gave, output you expect and what is the output that came?
1) Don't use "val" variable as you don't need it anymore :
amount = JOptionPane.showInputDialo g(null,"Pl ease enter amount to be financed:", " ", JOptionPane.QUESTION_MESSA GE);
amountValue = Double.parseDouble(amount) ;
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
// val = Integer.parseInt(amount);
if (amountValue < 0.0){
JOptionPane.showMessageDia log(null, "Amount cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (amountValue > 2000000.0) {
JOptionPane.showMessageDia log(null, "Amount cannot exceed $2,000,000", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
2)
>> if (val > 0) {
do you mean :
if (endAmount>0.0) {
?
3) This part of code should be outside the if block, otherwise response is not initialized when the condition is false.
response = JOptionPane.showConfirmDia log(null," Would you like to perform another calculation?",
"Try Again?",JOptionPane.YES_NO _OPTION);
amount = JOptionPane.showInputDialo
amountValue = Double.parseDouble(amount)
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
// val = Integer.parseInt(amount);
if (amountValue < 0.0){
JOptionPane.showMessageDia
continue;
}
else if (amountValue > 2000000.0) {
JOptionPane.showMessageDia
continue;
}
}
2)
>> if (val > 0) {
do you mean :
if (endAmount>0.0) {
?
3) This part of code should be outside the if block, otherwise response is not initialized when the condition is false.
response = JOptionPane.showConfirmDia
"Try Again?",JOptionPane.YES_NO
ASKER
I get the following error when i updated this section of the code:j ava:122: operator > cannot be applied to java.lang.String,double. Updated code it below. I think i moved outside of if statement, did i do something wrong??
if (endAmount > 0.0) {
^
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
if (endAmount > 0.0) {
JOptionPane.showMessageDia log(null,e ndAmount," Informatio n",JOption Pane.INFOR MATION_MES SAGE);
// JOptionPane.showMessageDia log(null," Your monthly mortgage payment is " + payment,"Information",JOpt ionPane.IN FORMATION_ MESSAGE);
}
{
response = JOptionPane.showConfirmDia log(null," Would you like to perform another calculation?",
"Try Again?",JOptionPane.YES_NO _OPTION);
}
}
while (response == 0);
}
}
// End of program
if (endAmount > 0.0) {
^
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
if (endAmount > 0.0) {
JOptionPane.showMessageDia
// JOptionPane.showMessageDia
}
{
response = JOptionPane.showConfirmDia
"Try Again?",JOptionPane.YES_NO
}
}
while (response == 0);
}
}
// End of program
>> if (endAmount > 0.0)
I didn't saw it was a String, instead remove the if condition.
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
JOptionPane.showMessageDia log(null,e ndAmount," Informatio n",JOption Pane.INFOR MATION_MES SAGE);
// JOptionPane.showMessageDia log(null," Your monthly mortgage payment is " + payment,"Information",JOpt ionPane.IN FORMATION_ MESSAGE);
response = JOptionPane.showConfirmDia log(null," Would you like to perform another calculation?",
"Try Again?",JOptionPane.YES_NO _OPTION);
}
while (response == 0);
}
}
// End of program
I didn't saw it was a String, instead remove the if condition.
String endAmount = "Your monthly mortgage payment is " + df.format(payment);
JOptionPane.showMessageDia
// JOptionPane.showMessageDia
response = JOptionPane.showConfirmDia
"Try Again?",JOptionPane.YES_NO
}
while (response == 0);
}
}
// End of program
ASKER
thanks that works. The mortgage amount is still off. I think i need to divide the percentage rate by 100 to get the correct calculation. Is there a way to do that?
rateValue = Double.parseDouble(rate) / 100.0;
As you don't need the val variable, remove the line
int val = 0;
and recompile. If you get errors, your code still use it, and need to be corrected.
As you don't need the val variable, remove the line
int val = 0;
and recompile. If you get errors, your code still use it, and need to be corrected.
ASKER
that worked. the calculated amount seems right. I was running program to make sure the if else if statements work at when you emter the amounts greater than what i have set the limit , the program accepts it. I have a gui box that is suppose to pop up and say there is an error. Are the statements wrong?
amount = JOptionPane.showInputDialo g(null,"Pl ease enter amount to be financed:", " ", JOptionPane.QUESTION_MESSA GE);
amountValue = Double.parseDouble(amount) ;
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
//val = Integer.parseInt(amount);
if (val < 0.0){
JOptionPane.showMessageDia log(null, "Amount cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 2000000.00) {
JOptionPane.showMessageDia log(null, "Amount cannot exceed $2,000,000", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
rate = JOptionPane.showInputDialo g(null,"Pl ease enter annual finance rate:", " ", JOptionPane.QUESTION_MESSA GE);
// rateValue = Double.parseDouble(rate);
// rateValue = Integer.parseInt(rate);
rateValue = Double.parseDouble(rate) / 100.0;
try {
// val = Integer.parseInt(rate);
if (val <0){
JOptionPane.showMessageDia log(null, "Annual Finance rate cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 14.0) {
JOptionPane.showMessageDia log(null, "Annual Finance Rate cannot exceed 14%", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia log(null, "Error, invalid entry", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
term = JOptionPane.showInputDialo g(null,"Pl ease enter months/term of loan:", " ", JOptionPane.QUESTION_MESSA GE);
termValue = Double.parseDouble(term);
try {
// val = Integer.parseInt(term);
if (val <0){
JOptionPane.showMessageDia log(null, "Months/Term cannot be less than 0", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
else if (val > 480) {
JOptionPane.showMessageDia log(null, "Months/Term cannot exceed 480 months", "Error", JOptionPane.ERROR_MESSAGE) ;
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMes
amount = JOptionPane.showInputDialo
amountValue = Double.parseDouble(amount)
try {
// parseInt is a method of class Integer. parseInt converts a string into an integer value
//val = Integer.parseInt(amount);
if (val < 0.0){
JOptionPane.showMessageDia
continue;
}
else if (val > 2000000.00) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
rate = JOptionPane.showInputDialo
// rateValue = Double.parseDouble(rate);
// rateValue = Integer.parseInt(rate);
rateValue = Double.parseDouble(rate) / 100.0;
try {
// val = Integer.parseInt(rate);
if (val <0){
JOptionPane.showMessageDia
continue;
}
else if (val > 14.0) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMessageDia
continue;
}
term = JOptionPane.showInputDialo
termValue = Double.parseDouble(term);
try {
// val = Integer.parseInt(term);
if (val <0){
JOptionPane.showMessageDia
continue;
}
else if (val > 480) {
JOptionPane.showMessageDia
continue;
}
}
catch(Exception e) {
// Error with the amount
JOptionPane.showMes
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I overlooked that. thank you so much, is running perfect. Thanks for all of you help.
:-)
That's a different problem than: >> How do you convert a string to a percentage rate?
What symbol does it say is unrecognized?