Skip to main content
0 online

Sipping Java

theremin by thereminOG 2002 · Apr 12, 2006 · 247 views

What to do with my first proper Java program...

I know how easy this is gonna be for Java programmers, and I'm sorta asshamed of posting the enquiry, but I'm not familiar with Java syntax yet really so anyway here is what needs to happen. . .

Purpose: Calculating property tax

How: the tax is based on 92% of the assessed value of the property & the tax rate is $1.05 for each $100 of assessed value. (The user gets prompted to enter assessed value of the property and from that, the respective information gets outputed to both the screen and a file. The output gets formatted to 2 decimal places)

Example:
Assessed Value: 100000.00 (User inputed & Output to screen & a file)
Taxable Amount: 92000.00 (Output to screen & a file)
Tax Rate for each 100.00: 1.05 (Output to screen & a file)
Property Tax: 966.00 (Output to screen & a file)

Help? Tips? Source?

:)

To contribute to the discussion, please log in.

40 Comments

theremin #6 thereminOG 2002

Need help on this working properly... it outputs a wrong result.. is it just the math operation at the bottom? What should the equation read as?

private JButton buttonCalc;

public Calculator() {
initComponents();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();

// Add Listeners
buttonCalc.addActionListener(this);
}

public void initComponents() {
//Initialize Components
panelAdder = new JPanel();
labela = new JLabel("Amount");
textFieldAmount = new JTextField();
labelt = new JLabel("Term");
textFieldTerm = new JTextField();
labelr = new JLabel("Rate");
textFieldRate = new JTextField();
textFieldResult = new JTextField();
buttonCalc = new JButton("Calculate");

//Set Object Attributes
textFieldResult.setEditable(false);
textFieldResult.setColumns(8);
textFieldAmount.setColumns(6);
textFieldTerm.setColumns(2);
textFieldRate.setColumns(2);

Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());

//Lets add the components to the panel
panelAdder.add(labela);
panelAdder.add(textFieldAmount);
panelAdder.add(labelt);
panelAdder.add(textFieldTerm);
panelAdder.add(labelr);
panelAdder.add(textFieldRate);
panelAdder.add(buttonCalc);
panelAdder.add(textFieldResult);

contentPane.add(panelAdder);
}

public static void main(String [] args) {
Calculator frame = new Calculator();
}

private void setResultValue() {
double amount = Double.parseDouble (textFieldAmount.getText());
double term = Integer.parseInt(textFieldTerm.getText());
double rate = Double.parseDouble(textFieldRate.getText()) / 100.;
double result = amount * ( rate * Math.pow ( ( 1 + rate ), term ) ) / ( Math.pow( ( 1 + rate ), term ) - 1 );

textFieldResult.setText(Double.toString(result));
}

public void actionPerformed(ActionEvent event) {
System.out.println("Action Button");
String command = event.getActionCommand();
if ("Calculate".equals(command)) { setResultValue(); }
}
}

D
#6.1 dgiaimoOG 2003

What are you trying to calculate here?

theremin #6.1.1 thereminOG 2002

Output the Monthly Mortgage Payment, from what the user inputted for amount, term (years), and rate (interest rate)

iwz #6.2 iwz

Try dividing the rate by 1200 instead of 100

theremin #6.2.1 thereminOG 2002

hrm. When I test it with that change, and use 350000 for amount, 30 for term and 7 for rate, the result is 1.16753711824

iwz #6.2.1.1 iwz

no, it's not. (scroll left in the result box)

theremin thereminOG 2002

Oh, I feel really stupid. It does work then, just gotta fix the display of the calculation.

D
#6.2.2 dgiaimoOG 2003

Shouldn't the term be expressed in months as well, rather than years?

theremin #6.2.2.1 thereminOG 2002

I don't think so. I don't want it to. 12751.16753711824 is definately not a good thing tho. Monthly payment of 12,751 for $350,000 over 30 years on 7 percent interest rate is WAY off to say the least.

D
dgiaimoOG 2003

What I mean is, you should multiply the term variable by 12 before plugging it into your formula. That 12,000 figure is definitely wrong. It should be around $2300.

theremin thereminOG 2002

If the mentioned changes are applied to now read as:

double term = Integer.parseInt(textFieldTerm.getText()) / 12;
double rate = Double.parseDouble(textFieldRate.getText()) / 1200;
double result = amount * ( rate * Math.pow ( ( 1 + rate ), term ) ) / ( Math.pow( ( 1 + rate ), term ) - 1 );

I get the calculation 176532.73438581926 using the same test input figures as I did to test it before.

So, not working any better I'm afraid.

D
dgiaimoOG 2003

It should be:

double term = Integer.parseInt(textFieldTerm.getText()) * 12;

theremin thereminOG 2002

Sometimes I'm just not thinking too clearly when it comes to math. Thanks, that's seems to have worked. I got 2328 and change after running it this time. So, now what's left is changing how the result displays, so I don't get all of those extra unneeded numbers. That's easy tho. After that, I'm gonna have to add some more features to it tho, to make it look like a better final project.

theremin thereminOG 2002

I tried get the output of the result to show just two numbers after the decimal, but can't get it to. What do I have to do?

D
dgiaimoOG 2003

Instead of using:

textFieldResult.setText(Double.toString(result));

in the setResultValue method try the following:

DecimalFormat myFormat = new DecimalFormat("#,###,###,##0.00");
StringBuffer myResult = myFormat.format(result, null, null);
testFieldResult.setText(myResult.toString());

I think this should work.

theremin thereminOG 2002 dgiaimo

Calculator.java:72: cannot find symbol
symbol : class DecimalFormat
location: class Calculator
DecimalFormat myFormat = new DecimalFormat("#,###,###,##0.00");
^
Calculator.java:72: cannot find symbol
symbol : class DecimalFormat
location: class Calculator
DecimalFormat myFormat = new DecimalFormat("#,###,###,##0.00");
^
Calculator.java:74: cannot find symbol
symbol : variable testFieldResult
location: class Calculator
testFieldResult.setText(myResult.toString());
^
3 errors

D
dgiaimoOG 2003 theremin

You need to import java.text.DecimalFormat. Also, I made a typo. It should be textFieldResult.

theremin thereminOG 2002 dgiaimo

Now this happens after the Calculate button is hit :(

Action Button
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.text.DecimalFormat.format(Unknown Source)
at Calculator.setResultValue(Calculator.java:75)
at Calculator.actionPerformed(Calculator.java:85)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

D
dgiaimoOG 2003 theremin

Hmm... Looks like I was reading the javadoc wrong. Try this:

DecimalFormat myFormat = new DecimalFormat("#,###,###,##0.00");
textFieldResult.setText(myFormat.format(result));

I even tested this this time, and it worked for me.

theremin thereminOG 2002 dgiaimo

Big thanks mate. That did the trick.

theremin #5 thereminOG 2002

Actually, there always seems to be a little noise that is enough to prevent me from being able think straight and clear. ugh!

theremin #4 thereminOG 2002

Quite a lot to do with this one.. so Far I have a class that looks like

public class Person
{
private String firstName;
private String lastName;

public Person()
{
firstName = "";
lastName = "";

}

public Person(String first, String last)
{
setName(first, last);
}

public String toString()
{
return (firstName + " " + lastName);
}

public void setName(String first, String last)
{
firstName = first;
lastName = last;
}

public Person setLastName(String last)
{
lastName = last;

return this;
}

public Person setFirstName(String first)
{
firstName = first;

return this;
}

public String getFirstName()
{
return firstName;
}

public String getLastName()
{
return lastName;
}
}

So how would I set the last name only
Check whether a given last name is the same as the last name of this person
Return true if 2 objects contain the same last name (Using equals method)
Use makecopy to copy the instance variables of a Person object into another Person object
Add the copy constructor
Write the definitions of the methods of the class Person to implement the operations for this class

There's some other stuff as well, but I'll forgo mentioning more.

iwz #4.1 iwz

are you asking for the answers to those questions? because they're all pretty straightforward.

how much help are you looking for?

theremin #4.1.1 thereminOG 2002

haha Yeh, lots. But, guess I'll just hafta do my best on this. :-\ hrm
Guess Java isn't my cup of tea yet..

iwz #4.2 iwz

Well, here's something to get you started:

"So how would I set the last name only"

Person person = new Person();
person.setLastName("Smith");

or
Person person = new Person(null, "Smith");

"Check whether a given last name is the same as the last name of this person"

String lastName = "Smith";
Person person1 = new Person( "John", "Smith" );
Person person2 = new Person( "Jane", "Johnson" );
System.out.println( person1.getLastName.equals( lastName ) );
System.out.println( person2.getLastName.equals( lastName ) );

theremin #4.2.1 thereminOG 2002

That is kind. Thank you.

iwz #4.2.1.1 iwz

here's a bonus equals method you can add to the Person class:

public boolean equals( Object o )
{
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;

final Person person = (Person)o;

if ( lastName != null ? !lastName.equals( person.lastName ) : person.lastName != null ) return false;

return true;
}

theremin thereminOG 2002

Well this is what I did.. tell me if it looks right. It compiles without errors at least. hehe

public class Person
{
private String firstName;
private String middleName;
private String lastName;


public Person()
{
firstName = "";
middleName = "";
lastName = "";

}

public Person(String first, String middle, String last)
{
setName(first, middle, last);
}

public String toString()
{
return (firstName + " " + middleName + " " + lastName);
}

public void setName(String first, String middle, String last)
{
firstName = first;
middleName = middle;
lastName = last;
}

public Person setLastName(String last)
{
lastName = last;

return this;
}

public Person setMiddleName(String middle)
{
middleName = middle;

return this;
}

public Person setFirstName(String first)
{
firstName = first;

return this;
}

public String getFirstName()
{
return firstName;
}

public String getMiddleName()
{
return middleName;
}

public String getLastName()
{
return lastName;
}

public boolean equals(Person otherPerson)
{
return(firstName == otherPerson.firstName && lastName == otherPerson.lastName);
}

public void makeCopy(Person otherPerson)
{
firstName = otherPerson.firstName;
middleName = otherPerson.middleName;
lastName = otherPerson.lastName;
}

public Person getCopy()
{
Person temp = new Person();

temp.firstName = firstName;
temp.middleName = middleName;
temp.lastName = lastName;

return temp;
}
}

iwz iwz

Looks pretty good. I'd change a couple of things tho.

== is not proper for comparing Strings. use .equals() instead.

so this firstName == otherPerson.firstName && lastName == otherPerson.lastName should be like this firstName.equals( otherPerson.firstName) && lastName.equals(otherPerson.lastName)

Also, the makeCopy(Person) method may be more appropriate as a constructor instead of a method.

public Person( Person person )
{
firstName = person.firstName;
middleName = person.middleName;
lastName = person.lastName;
}

Also, for the getCopy method, take a look at the Cloneable interface, and the clone() method. It may give you a cleaner implementation. But that depends on your requirements, of course.

theremin thereminOG 2002

Oh, we didn't talk about a clone() method yet. Thanks for all the help as usual.

D
dgiaimoOG 2003

Your equals method shouldn't throw an Exception if you pass in null, as this one will.

deanh77 deanh77Founder

yes check that the otherPerson is null, and return false if it is. and use .equals on Strings like Ian said, since == is a reference equality in objects (i.e. these two variables point to the same object in memory), but String's equals() does an equality check on the contents of the Object (the internal array of characters that make up the String).

theremin #3 thereminOG 2002

What's wrong with this code?

import java.util.*;

public class Exercise14
{
static Scanner console = new Scanner(System.in);

public static void main(String [] args)
{
int first, third;
IntClass second, fourth;

first = 3;
second = new IntClass(4);
third = 6;
fourth = new IntClass(7);

System.out.println(first + " " + second.getNum()
+ " " + third + " "
+ fourth.getNum());
getData(first, second, third, fourth);
System.out.println(first + " " + second.getNum()
+ " " + third + " "
+ fourth.getNum());
fourth.setNum(first * second.getNum() + third +
fourth.getNum());
getData(third, fourth, first, second);
System.out.println(first + " " + second.getNum()
+ " " + third + " "
+ fourth.getNum());
}

public static void getData(int a, IntClass b, int c, IntClass d)

{
a = console.nextInt();
b.setNum(console.nextInt());
c = console.nextInt();
d.setNum(console.nextInt());

b.setNum(a * b.getNum() - c);
d.setNum(b.getNum() + d.getNum());
}

}

I'm getting this when I compile:

Exercise14.java:32: cannot find symbol
symbol : class IntClass
location: class Exercise14
public static void getData(int a, IntClass b, int c, IntClass d)
^
Exercise14.java:32: cannot find symbol
symbol : class IntClass
location: class Exercise14
public static void getData(int a, IntClass b, int c, IntClass d)
^
Exercise14.java:10: cannot find symbol
symbol : class IntClass
location: class Exercise14
IntClass second, fourth;
^
Exercise14.java:13: cannot find symbol
symbol : class IntClass
location: class Exercise14
second = new IntClass(4);
^
Exercise14.java:15: cannot find symbol
symbol : class IntClass
location: class Exercise14
fourth = new IntClass(7);
^
Exercise14.java:24: operator + cannot be applied to int,IntClass.getNum
fourth.setNum(first * second.getNum() + third +
^
6 errors

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

iwz #3.1 iwz

First, have you created the IntClass? and is it in the same package as Exercise14?

Your compiler is not able to find IntClass. So, if you've already created it, then make sure you compile everything all together, like javac *

If you haven't created IntClass yet, here's what it should look like:

public class IntClass
{
private int num;

public IntClass( int num )
{
this.num = num;
}

public int getNum()
{
return num;
}

public void setNum( int num )
{
this.num = num;
}
}

theremin #3.1.1 thereminOG 2002

I'm further humbled. Thanks. Big help.

theremin #2 thereminOG 2002

After just trying to compile what I coded, I made what I hope are appropiate changes. . and so now my program looks like . .

import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;

public class PropertyTax
{
public static void main(String [] args)
throws FileNotFoundException
{
String inputAssessedValueString;
double inputAssessedValue;
double taxableAmount;
double taxRate_hundreds;
double finalPropertyTax;

inputAssessedValueString = JOptionPane.showInputDialog
("Enter assessed value");

inputAssessedValue = Double.parseDouble(inputAssessedValueString);

taxableAmount = 0.92 * inputAssessedValue;
taxRate_hundreds = taxableAmount / 100;
finalPropertyTax = taxRate_hundreds * 1.05;

JOptionPane.showMessageDialog(null,
String.format("The Assessed Value equals $ %.2f%n",inputAssessedValue)
+ String.format("Taxable Amount equals $ %.2f%n", taxableAmount)
+ String.format("Tax Rate each $ 100.00: $ 1.05")
+ String.format("Property Tax equals %.2f%n", finalPropertyTax),
"Property Tax Calculation",
JOptionPane.INFORMATION_MESSAGE);

PrintWriter outFile = new PrintWriter("a:\\proptax.txt");

outFile.close();
}
}

iwz #2.1 iwz

looks like you've got something going! i'll have to take a look at this later, as I'm just about leaving work

D
#2.2 dgiaimoOG 2003

A few things.

1) You haven't actually written anything to your file.

2) You really never want to use doubles or floats for monetary quantities. The rounding errors will kill you. Much better to use a dedicated Currency class that uses fixed point arithmetic, though for this exercise it probably doesn't matter.

3) It's usually good programming practice to give constants names rather than embedding literals, but, again, for this exercise it probably doesn't matter.

Other than that it appears to be good, especially if this is your first time trying to write a Java program.

iwz #1 iwz

Well, your first task could be to come up with a nice object model (on a high, pseudo level).

What object(s) do you think you might need for this task?

theremin #1.1 thereminOG 2002

Well, I went ahead and just tried to do all the coding as best as I could come up with. How does this look?

import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;

public class PropertyTax
{
public static void main(String[] args)
{
double inputAssessedValue;
double taxableAmount;
double taxRate_hundreds;
double finalPropertyTax;

inputAssessedValue = JOptionPane.showInputDialog
("Enter assessed value");
taxableAmount = 0.92 * inputAssessedValue;
taxRate_hundreds = taxableAmount / 100;
finalPropertyTax = taxRate_hundreds * 1.05;

JOptionPane.showMessageDialog(null,
String.format("The Assessed Value equals $ %.2f%n",inputAssessedValue);
+ String.format("Taxable Amount equals $ %.2f%n", taxableAmount);
+ String.format(Tax Rate for each $ 100.00: $ 1.05);
+ String.format("Property Tax equals %.2f%n", finalPropertyTax),
"Property Tax Calculation";
JOptionPane.INFORMATION_MESSAGE);

PrintWriter outFile = new PrintWriter("a:\\proptax.txt")

outFile.close();
}
}

Welcome Back to eZabel

It's been a while. Here's what's new.

eZabel Lore

A complete history of our community — stats, Hall of Fame, legendary threads, and more.

View the Lore →

Curator Commentary

Look for the blue speech bubbles on threads, profiles, and news — notes and context from iwz.

Everything Preserved

All 225,969 pieces of content from 2000–2014 are here — forums, messages, journals, photos, polls, and events.