Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: converting String to int

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.

like image 631
willmer Avatar asked Jul 26 '11 20:07

willmer


People also ask

Can we convert string to int in Java?

The method generally used to convert String to Integer in Java is parseInt() of String class.

How do you change a string to an int C++?

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.


2 Answers

Change

try {     myNum = Integer.parseInt(myString.getText().toString()); } catch(NumberFormatException nfe) { 

to

try {     myNum = Integer.parseInt(myString); } catch(NumberFormatException nfe) { 
like image 89
citizen conn Avatar answered Oct 08 '22 11:10

citizen conn


It's already a string? Remove the getText() call.

int myNum = 0;  try {     myNum = Integer.parseInt(myString); } catch(NumberFormatException nfe) {   // Handle parse error. }
like image 41
JK. Avatar answered Oct 08 '22 09:10

JK.