Results 1 to 6 of 6
- 09-06-2010, 02:29 AM #1
Member
- Join Date
- Sep 2010
- Posts
- 47
- Rep Power
- 0
Problems when multiplying numbers from a string
Hello everyone. I am writing a program in which I have a string, called num, that is a very long number. I am trying to pull the first few digits of that number and multiply them together, however when I do, I get a very big result (billions of times larger than it should). Here is my code:
Since this didn't work, I put each in its own separate int and tried multiplying them again:Java Code:int indx = 0; //just a variable for the index of the string String num = "12345678901234567890"; int product = ((num.charAt(indx))*(num.charAt(indx + 1))*(num.charAt(indx + 2))*(num.charAt(indx + 3))*(num.charAt(indx + 4)));
And I still got the same result. When I print each digit separately, I get the right values, but when I multiply them, I get a crazy number. Please Help. Thanks in advance.Java Code:int aa = (num2.charAt(indx)); int ab = (num2.charAt(indx + 1)); int ac = (num2.charAt(indx + 2)); int ad = (num2.charAt(indx + 3)); int ae = (num2.charAt(indx + 4)); int aaaa = aa*ab*ac*ad*ae; System.out.println(aaaa);
- 09-06-2010, 02:46 AM #2
To see what values you are working with, extract a single character digit from the String and print it as an int.
The char '1' is not equal to the integer 1. You need to convert the characters to integer values. See the Character class and the Integer class for methods to do that.
- 09-06-2010, 02:59 AM #3
Member
- Join Date
- Sep 2010
- Posts
- 47
- Rep Power
- 0
Thanks a lot, I had no idea that they were different. Upon doing a little research, I learned about a method called 'atoi'. Would this do the trick in my case?
- 09-06-2010, 03:01 AM #4
Try it and see. Let us know if it works.Would this do the trick
atoi looks like a c function. Go check your research again. You need to use a method of a Java class
- 09-06-2010, 03:23 AM #5
Member
- Join Date
- Sep 2010
- Posts
- 47
- Rep Power
- 0
You were exactly right! Atoi does seem to be a C method lol.. Would parseInt work?
-
Last edited by Fubarable; 09-06-2010 at 04:03 AM.
Similar Threads
-
Multiplying Values of an Array
By brmcdani in forum New To JavaReplies: 3Last Post: 02-06-2010, 04:00 AM -
Multiplying Variables
By rnavarro9 in forum New To JavaReplies: 4Last Post: 12-03-2009, 08:10 AM -
add all the numbers in a string
By gibson.nathan in forum New To JavaReplies: 29Last Post: 09-30-2009, 06:14 PM -
parsing numbers in a string
By rsoler in forum Advanced JavaReplies: 4Last Post: 03-31-2009, 06:05 AM -
validating a string for numbers and letters?
By lockmac in forum New To JavaReplies: 1Last Post: 08-09-2007, 09:17 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks