-
adding numbers
i am trying to add every number (i had 141062). i broke them apart, and convert them to ints. then i can add them. am i going about this the right way? here is what i have so far:
Code:
for (count = 0; i<doubledDigits.length(); i++)
{
numbersToAdd2 = doubledDigits.charAt(i); // gets 2610 as a string
numbers4 = Integer.parseInt(numbersToAdd2); //string==>int
numbers3 = numbers3 + numbers4;
}
sorry about the variables... please ignore for now :p
-
Are you trying to calculate digit sum of a number?
Looks like it's correct though, does it compile and run?
-
yes, i am.
sorry, maybe this is better?...
Code:
for (count = 0; i<doubledDigits.length(); i++)
{
numbers2 = doubledDigits.charAt(i);
numbers3 = numbers2 + numbers3;
}
still doesn't work tho... i get zip!
-
It should work if you loop through, parse each and add it to the sum.
You can also do it with a number directly using / and %.
-
here is what i have:
Code:
for (i = 0; i < lengthCC ; i += 2) // get every other number (start 1 from the right)
{
nextDigit = (Character.getNumericValue(creditCardNumber.charAt(i)));
doubledNextDigit = (nextDigit*2); // multiply that number at i by 2
numbers = Integer.toString (doubledNextDigit);
doubledDigits = doubledDigits + numbers; // doubledDigits is in string form...
}
System.out.println("Your double digits are: " + doubledDigits); //WORKS!!! (261014)
String string = "";
for (count = 0; i<doubledDigits.length(); i++)
{
numbersToAdd2 = doubledDigits.charAt(i); // gets 2610 as a string
numbers4 = Integer.parseInt(numbersToAdd2); //string==>int
numbers3 = numbers3 + numbers4;
}
i get a cannot find symbol for the parsing, and incompatible types for numbers3 + 4... i guess the first problem creates a second problem :(
numbersToAdd2 was initialized as a int... doubledDigits is a string... so numbersToAdd2 should be an int, right?
-
In the original part try using the strong substring method instead. Then parse to integer and add it to the sum. What is the goal of the first loop?
-
to double each of the digits. i then set it to a string
i did this:
Code:
String string = "";
String doubledDigits = "";
int numbers5 = 0;
int numbers3 = 0;
for (count = 0; i<doubledDigits.length(); i++)
{
string = doubledDigits.substring(i); // gets 2610 as a string
numbers5 = Integer.parseInt(string); //string==>int
numbers3 = numbers3 + numbers5;
}
and still got 0.
-
If this is your actual code then the doubleDigits string is empty (has a length of zero) so it never enters the loop and the value of numbers3 (please use more appropriate variable names) never changes.