+ 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! :)
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. š
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