0

What is the difference between >n=in.nextInt and >n=Integer.parseInt?

I'd like to know why I get an error while using them in differently in different programs

22nd Jul 2017, 4:50 PM
Veronica Ebenezer
Veronica Ebenezer - avatar
2 Answers
+ 2
This is Java, right? using nextInt, you can only read integers. Anything else will cause an error Integer.parseInt converts a String to integer. If String contains symbols that are not integers, it will also cause an error
22nd Jul 2017, 5:08 PM
Eligijus Silkartas
Eligijus Silkartas - avatar
+ 2
Er.. In what language? Java?? If it is Java, this is an error because the syntax doesn't make any sense. int n = in.nextInt(); // Parethesis are NEEDED I assume 'in' is the name of the scanner. So, this is expecting an int from the user as input. int n = Integer.parseInt(); What are you parsing here? That's the problem, you're not converting anything. Explanation/ Integer is a class. parseInt() is a method in that class. What it does is, it attempts to convert whatever is in the parameters to an int. Example/ int n = Integer.parseInt("5"); // this will convert "5" to 5 So, nextInt() will expect and return the int from the users input. While parseInt() will attempt to convert whatever you place in it's arguments (parameters) to the type int. Not similar at all.
22nd Jul 2017, 5:11 PM
Rrestoring faith
Rrestoring faith - avatar