#MOOC JAVA

1 messages · Page 1 of 1 (latest)

cyan sparrow
#

Even though the solution code is same as my code but i am not passing the test. What might be the reason?

lapis wharfBOT
#

<@&987246399047479336> please have a look, thanks.

cyan sparrow
brittle arch
#

You should be reading the pages and year by parsing a line of input each time - the .nextInt() method shouldn't be used for interactive input.

eg

int pages = Intreger.parseInt(scnaner.nextLine());
cyan sparrow
#

What's the difference tho? since both of them take input from the users.

#

@brittle arch

#

one takes in int another one in string

#

at the end in this case we just need int

weary ravine
#

nextLine consumes the \n symbol as well

#

nextInt does not

brittle arch
#

You're expecting the user to enter a line of input, but nextInt() doesn't read a line, it reads up to the end of something that looks like an int. And if the input doesn't look like an int you get an odd error.

You're also leaving the line separator behind.

weary ravine
#

yeah, nothing stops the user from inputting whatever he wants

brittle arch
#

Essentially Scanner was created to be used in several different scenarios. Those methods do not suit being used for interactive input.

#

But you don't have to trust us... Here's a quote from Brian Goetz (Java Platform Architect) on replacing this tool.

Scanner has a ton of complexity in it that can easily trip up
beginners. The main sin (though there are others) is that input and
parsing are complected (e.g., nextInt), which only causes more problems
(e.g., end of line issues.) Reading from the console is clearly a ()
-> String operation. The input() method does one thing, which is get a
line of text. That's simple.

cyan sparrow
#

it reads up to the end of something that looks like an int.

brittle arch
#

Because it's intended for structured data reading, when you know the input complies with the expected pattern.

cyan sparrow
#

if the input is 58/n then Int will read 58 leaving /n?

brittle arch
#

The method .nextInt() isn't meant to take a line of input from a user as an int. It's intended to take an int from a stream of characters.

cyan sparrow
#

gotcha

#

thanks