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.

16th Apr 2018, 2:54 PM
Jan Štěch
Jan Štěch - avatar
5 Respostas
+ 3
Use Integer.parseInt("YourString");
16th Apr 2018, 2:59 PM
Jonas Schröter
Jonas Schröter - avatar
+ 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)"); }
16th Apr 2018, 4:05 PM
cyk
cyk - avatar
+ 2
Thanks a lot. 😃
16th Apr 2018, 3:19 PM
Jan Štěch
Jan Štěch - avatar
0
Donna Thank you too, but why is there the for cycle? It works fine without it too.😕
16th Apr 2018, 8:19 PM
Jan Štěch
Jan Štěch - avatar