• Post Reply Bookmark Topic Watch Topic
  • New Topic

Int VS. Double  RSS feed

 
Davey Lopez
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello I'm trying to write a program where the user has the option to enter either an int or double but whatever input I enter just gets cast to a double. Do I even have the right Idea by using if else statements?


 
Paul Clapham
Sheriff
Posts: 22816
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, "42" is a valid double value. So your code which asks if there is a double value next would accept that if you keyed it in. Perhaps you shouldn't look first for a double value, then?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Davey Lopez wrote:Do I even have the right Idea by using if else statements?

Nothing particularly wrong with it except, as Paul says, that int is more restrictive than double, so you might want to swap them around. Aternatively, simply accept a double, and then see whether it:
(a) has a "fractional" part.
(b) fits into an int.
If (a) is false, and (b) is true, then the value is a valid int.

Winston
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are all sorts of ways you can validate a String as an int; you can use regexes, or use a Scanner on it and the hasNextInt method. Those are only two ways; there are bound to be more.
 
Davey Lopez
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All right thanks everyone that worked
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome but please show us what you used.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!