Suppose i want to create a method that takes a number as a string and return its number form. Like
getNumber("123456");
public int getNumber(String number) {
//No library function should used. Means i can't do Integer.parseInteger(number).
} //end of getNumber()
How can i implement that method like
public int getNumber(String number) {
for (int i=0; i<number.length; i++) {
char c = number.getCharacter(i);
///How can i proceed further
} //end of for()
} //end of getNumber()
Without using a library function, subtract the character
'0'from each numeric character to give you itsintvalue, then build up the number by multiplying the current sum by 10 before adding the next digit’sìntvalue.Java 7
Java 8
This works primarily because the characters
0-9have consecutive ascii values, so subtracting'0'from any of them gives you the offset from the character'0', which is of course the numeric equivalent of the character.Disclaimer: This code does not handle negative numbers, arithmetic overflow or bad input.
You may want to enhance the code to cater for these. Implementing such functionality will be instructive, especially given this is obviously homework.
Here’s some test code:
Output: