xxxxxxxxxx
#include <iostream>
#include <string>
using namespace std;
int main() {
string digitStr = "1";
int digit = stoi(digitStr);
cout << "Converted digit: " << digit << endl;
return 0;
}
xxxxxxxxxx
int result = Integer.parseInt("500");
System.out.println(result) // prints 500 as int
xxxxxxxxxx
class scratch{
public static void main(String[] args) {
String str = "54";
int num = Integer.parseInt("54");
double doub = Double.parseDouble("54");
}
}
xxxxxxxxxx
//String to int , scanner, NumberFormatException,
Scanner scanner = new Scanner(System.in);
while (true) {
String input = scanner.next();
try {
int a = Integer.parseInt(input);
if (a == 0) {
break;
}
System.out.println(Integer.parseInt(input) * 10);
} catch (NumberFormatException e) {
System.out.println("Invalid user input: " + input);
}
}
xxxxxxxxxx
There are two methods available in java to convert string to integer.
One is
Integer.parseInt() method and another one is
Integer.valueOf() method. Both these methods are static methods
of java.lang.Integer class. Both these methods throw
NumberFormatException if input string is not a valid integer.
xxxxxxxxxx
String str = "12345"; // example string
int num = Integer.parseInt(str); // convert string to integer
System.out.println(num); // Output: 12345