I'm simply trying to convert a string that is generated from a barcode scanner to an int so that I can manipulate it by taking getting the remainder to generate a set number of integers. So far I have tried:
int myNum = 0; try { myNum = Integer.parseInt(myString.getText().toString()); } catch(NumberFormatException nfe) { }
and
Integer.valueOf(mystr);
and
int value = Integer.parseInt(string);
The first one gives me the error :The method getText() is undefined for the type String while the last two don't have any compile errors but the app crashes immediately when those are called. I thought it had to do with my barcode scanning intent method but I put it into the OnCreate and still got the error.
The method generally used to convert String to Integer in Java is parseInt() of String class.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
Change
try { myNum = Integer.parseInt(myString.getText().toString()); } catch(NumberFormatException nfe) {
to
try { myNum = Integer.parseInt(myString); } catch(NumberFormatException nfe) {
It's already a string? Remove the getText() call.
int myNum = 0; try { myNum = Integer.parseInt(myString); } catch(NumberFormatException nfe) { // Handle parse error. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With