Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

It's reading things wrong

 
Emily Smith
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to write a program that determines whether or not a number is a multiple of 3, using the "add the digits together, see if sum is divisible by 3" trick. So far, I've got:




But every time I try to run that, I get a huge number that's completely off and I realized that the number being added is the ASCII code (is that what it's called?). How do I get my program to read the numbers as integers instead of characters?
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch. Please paste the whole code inside the code tags. That way it becomes much more legible.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49388
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again. I have added the code tags as described here, and it looks a lot better.
You can try the numericValue method of the Character class, but you are better using the Integer class method which parses a String to an int. Then you need to know how to iterate the individual digits, possibly best done with a combination of the % and / operators.
 
Paul Mrozik
Ranch Hand
Posts: 117
Chrome Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Welcome again. I have added the code tags as described here, and it looks a lot better.
You can try the numericValue method of the Character class, but you are better using the Integer class method which parses a String to an int. Then you need to know how to iterate the individual digits, possibly best done with a combination of the % and / operators.


I'd probably do it this way:

1. Iterate each character of the String
2. parse each String character to, for example int x
3. Add the x to int total

But I'd like to know how to iterate each int digit using the % and / operators.


 
Campbell Ritchie
Sheriff
Pie
Posts: 49388
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are simpler ways to get numeric values than parsing a single char. If yo uare sure all the numbers will be decimal (or a smaller radix) you can use
c - '0'
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic