Question for the Scanner | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Question for the Scanner

Hello, guys! Can you tell me what is the difference between: Scanner sc = new Scanner(System.in); int a = sc.nextLine(); & int b = Integer.parseInt(sc.nextLine()); I know that the both will print the value that I will type in the console. But why we need this "parse" in the code? Also l remember that for String we don't need to use "parse". Why then for integer, double, or float etc. we should/can use this method? Thank you! :)

19th Oct 2017, 6:09 AM
Aleksandar Markov
Aleksandar Markov - avatar
2 Answers
+ 7
The first approach wouldn't work as user input will be always read as string, perhaps you mean:- int a = sc.nextInt(); If you need to perform arithmetic operation from user input then you'll need to perform the appropriate parsing. Otherwise you may leave it as it is since output will be in string as well. 😉
19th Oct 2017, 8:39 AM
Zephyr Koo
Zephyr Koo - avatar
0
Oo, now l i think i did understand it. It is really easy actually. So for example (when i write in the console 2): 1) in the first case: int a = sc.nextLine(); System.out.print(a+2); // It will print 22 2) And in the second: int a = Integer.parseInt(sc.nextLine()); System.out.println(a+2); //It will print 4
20th Oct 2017, 10:10 AM
Aleksandar Markov
Aleksandar Markov - avatar