how can i add values from a loop in java -


i've been given question uni in regards credit card statement says have string of numbers, convert these numbers separate integers increment them power of 10 depending on position in string using horners method have add values loop make 1 whole integer. know odd way convert string int assignment states have use horners method convert string rather use inbuilt java classes/methods

my question is, how can add separate weighted numbers , concatenate them 1 single number.

if helps example be,

given card number 1234, number weighted according position , length so:

1 - 1000 2 - 200 3 - 30 4 - 4 

then these added create whole number

1, 2, 3,4 ---> 1234

here code far

public static long toint(string digitstring) {     long answer = 0;     long val = 0;     string s = "";     (int j = 0; j < digitstring.length(); j++) {         val = digitstring.charat(j) - '0';         val = (long) (val * math.pow(10, (digitstring.length() - 1) - j));         system.out.println(val);      }     return answer; } 

most not following you, because sounds simple. return long (or integer) have sum these numbers:

public static long tolong(string digitstring) {     long answer = 0;     long val = 0;     (int j = 0; j < digitstring.length(); j++) {         val = digitstring.charat(j) - '0';         val = (long) (val * math.pow(10, (digitstring.length() - 1) - j));         answer += val; // here! :)         //system.out.println(val);     }     return answer; } 

please note not going work negative numbers, here more complex version:

public static long tolong(string digitstring) {     long answer = 0;     long val = 0;     boolean negative = false;     int j = 0;      if (digitstring.charat(0) == '-') {         negative = true;         j = 1;     } else if (digitstring.charat(0) == '+')         j = 1;      (; j < digitstring.length(); j++) {         if (!character.isdigit(digitstring.charat(j)))             throw new numberformatexception(digitstring);          val = digitstring.charat(j) - '0';         val = (long) (val * math.pow(10, (digitstring.length() - 1) - j));         answer += val;     }      return negative ? -answer : answer; } 

this code work negative numbers , weird numbers start + sign well. if there other character, throw exception.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -