r/learnjava • • Aug 22 '20

scan.nextInt vs Integer.valueOf(scan.nextLine())

I've been doing mooc.fi java course for a couple of weeks now and I noticed that every time they want an user to input a number, they use

int number = Integer.valueOf(scan.nextLine());

but I was curious what other parameters I can use with the scanner and I found out I can just type

int number = scan.nextInt();

which seems to be doing exactly the same thing. Is there any reason why would I want to use the longer one?

49 Upvotes

23 comments sorted by

6

u/RayjinCaucasian Aug 22 '20

When you use nextInt() it leaves a "\n" (newline character) in the buffer. The subsequent call on nextLine() will try to read a string up to a "\n", since the "\n" remains in the buffer it is then consumed immediately by the nextLine() call leaving you with an empty String. Using the Integer class methods combined with nextLine() allow for the parsing of the int and the consumption of the "\n".

1

u/_Mido Aug 22 '20 edited Aug 22 '20

Shouldn't then using nextInt() after nextLine() cause an error too? If nextInt() leaves a newline character in the buffer, I assume nextLine() does it as well. Since newline is not a number and nextInt() takes a number, I'd expect an error. But when I tested it in my sandbox project, no such thing happened.

2

u/RayjinCaucasian Aug 22 '20

The "\n" originates from the input stream (System.in i.e. keyboard) not from the method itself. nextInt() is looking for the next Int, nextLine() is looking for the next line. Making sense?

2

u/_Mido Aug 22 '20

nextLine() is looking for the next line

Ahh, for some reason I associated nextLine with hypothetical nextString(), especially since I cannot write

int number = scan.nextLine();

2

u/RayjinCaucasian Aug 22 '20 edited Aug 22 '20

That would just be next() which finds the next complete token up the next delimiter by the defualt which is whitespace. (I.e. a space). which is different that nextLine() where it's trying to grab everything before the "\n".

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextDouble--

Edit: Im realizing you probably meant the whole string as in "stuff that I wrote" not just a singular word.

5

u/Koyomii-Onii-chan Aug 22 '20

The .nextInt() leaves a new line character after you read a number. If you use nextLine() after nextInt() the new line character will be read ('\n')

int number = scan.nextInt()

String s = scan.nextLine() // this won't read the input you give, it will read '\n'

The issue above is resolved by adding a scan.nextLine() before the String but this will make the code confusing

int number = scan.nextInt()

scan.nextLine(); // this will read the new line character but please don't do this

String s = scan.nextLine() // now this will read the string that you give from input

Also if you have a large loop is better to use int number = Integer.valueOf(scan.nextLine());

3

u/_Mido Aug 22 '20 edited Aug 22 '20

I tested your code and it seems to be the case but I still don't understand why does

String s = scan.nextLine()

take something that happened before it as an input (the \n) instead of taking what I would write in the next line.

8

u/Koyomii-Onii-chan Aug 22 '20

nextInt() expects a number to be inserted. After you write your number you press enter. This enter is the new line character. So you input two things: the number + new line character(enter)

Since nextInt() will take only the number it ignores the \n and it remains there and nextLine() will take it

if I swap the order of these two lines in your example, there is no problem at all.

because nextLine() reads everything including the \n

I apologies if my explanation is bad

1

u/_Mido Aug 22 '20

I think I get it now. Thanks!

1

u/sportsroc15 Aug 22 '20

Good explanation.

2

u/bitemyshinymetalass0 Aug 22 '20

why is Integer.valueOf() preferred? does it bypass the new line problem with nextInt()?

2

u/Koyomii-Onii-chan Aug 22 '20

The full expression is Integer.valueOf(sc.nextLine()) . The sc.nextLine() is important because it read the whole line. Also it's important to know that sc.nextLine() returns a String. In your case, the whole line.

int x =  Integer.valueOf(sc.nextLine())

// if your input 3, what sc.nextLine() actually reads is 3 '\n'
After the reading the valueOf() comes in action and it takes the first number from your String and parses it to Integer. '\n' is ignored in this case

1

u/bitemyshinymetalass0 Aug 22 '20

Thanks! It's slick trick to use!

13

u/6t94twenty Aug 22 '20

scan.nextInt has a problem that u cannot take string input after athat (idk the cause), its better to use Integer.valueOf(scan.nextLine())

6

u/6t94twenty Aug 22 '20

U can also do Integer.parseInt

4

u/4K3b1g Aug 22 '20

I noticed that IntelliJ IDEA auto-suggests this when I use it.

2

u/Joe_Doblow Aug 22 '20

I’m curious too

2

u/4K3b1g Aug 22 '20

Thanks for asking this question! I was wondering the same thing but didn't ask.

1

u/desrtfx Aug 22 '20

The Scanner class and its caveats from the /r/javahelp wiki.

In short, if you know what you are doing and how .nextInt behaves it is perfectly fine to use the shorter. If you are not sure, the longer version is always a safe bet.

1

u/RayjinCaucasian Aug 22 '20

I was going to use that link but it wasn't working. It seems its still the case. It says "the wiki is disabled".

1

u/desrtfx Aug 23 '20

For some reason outside our control, the wiki only works on desktop, not on mobile.

I use rif is fun (ex. Reddit is fun) on my Android and can open wiki links.

1

u/abcoolynr Aug 22 '20

scan.nextInt() can be used without problem, it's just that you will have to put scan.next() to consume buffer or you can use scan.nextInt().useDelimiter('\n'); Hackerrank uses scan.skip(regular expression for \n\t\space etc); If you want you can use BufferedReader class which doesn't have this issue.

1

u/abcoolynr Aug 22 '20

int val= Integer.parseInt(String value) is used to convert string values to an integer values. This is mostly used in Web Application/Mobile Application for taking user input.