0
How to get int out of string in Java
Hello everyone. I need to know, how can I get an integer value saved in a string into an integer variable. Here is a simple example: Consider that input is "I am <num> years old" and I need to get the num value. int Age=0; Scaner scn = new Scanner(System.in); String input=scn.nextLine(); String [] text=input.split(" "); Age=text[2]; <-- This is what doesn't work. Casting doesn't work.
5 Answers
+ 3
Use Integer.parseInt("YourString");
+ 3
Be aware that parseInt throws an exception if your string is not indeed and integer so it is good to put it in a try block, especially if there is a chance the string could not contain an int
try{
int a = Integer.parseInt("YourString");
//everything else you want to do with a
}
catch (NumberFormatException ex){
System.out.print("The string is not an integer (or whatever)");
}
+ 2
Thanks a lot. đ
0
Donna
Thank you too, but why is there the for cycle? It works fine without it too.đ