Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

creating a calculator application - need some math help

 
charlie mills
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've created buttons that add, subtract, multiply and divide and these work fine.

I now need to add squared, cubed and sqaure root.

For the sqaured button, I wrote this but it's not working:

int total = totalsofar^2

what am i doing wrong?

also, how would i sqaure root?
 
charlie mills
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i've just discovered the Math class so I have answered my own questions there. However, now I have a new question

I previously had all my values stored as integers and then decided that I needed them stored as doubles.

so at the moment i have:
I'm not really sure how to describe it, but is it because I'm reading in Integers from the string? i'm unsure of how to get it to read in the decimals.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use "Double.parseDouble()" instead of "Integer.parseInt()".
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To warn, do not use floating points when doing precise arithmetic calculations. Use BigDecimal.

Also see http://docs.sun.com/source/806-3568/ncg_goldberg.html
 
Campbell Ritchie
Sheriff
Pie
Posts: 49751
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look here, you find the ^ operator does something completely different from what you thought.
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Math has a method called pow that does what you think ^ does. Or, for squares and cubes, simply calculate "totalsofar * totalsofar" or "totalsofar * totalsofar * totalsofar".
 
Campbell Ritchie
Sheriff
Pie
Posts: 49751
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calculators are never really precise; you can use a double, knowing that the imprecision will be slight. If you do get $1.10 - $0.99 = $0.109999999999999983465092374625 or similar, will that actually cause any problems?
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If so, follow Bauke's advice on BigDecimal.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic