Thursday, 15 June 2017

How do I convert a String to an int in Java?

Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code, but it could help others that are restricted like I was.



The first thing to do is to receive the input, in this case, a string of digits; I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";



Another limitation was the fact that I couldn't use repetitive cycles, therefore, a for cycle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:



 // Obtaining the integer values of the char 1 and 2 in ASCII
int semilastdigitASCII = number.charAt(number.length()-2);

int lastdigitASCII = number.charAt(number.length()-1);


Having the codes, we just need to look up at the table, and make the necessary adjustments:



 double semilastdigit = semilastdigitASCII - 48;  //A quick look, and -48 is the key
double lastdigit = lastdigitASCII - 48;


Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do.




We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:



 lastdigit = lastdigit/10;


This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:



 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2



Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:



 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"


And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:




  • No repetitive cycles


  • No "Magic" Expressions such as parseInt

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...