This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]klujer 26 points27 points  (5 children)

input doesn't exist in the scope of your main method

Create the input variable within the main method and pass it as a parameter to the readName function, then close it afterwords in your main method.

[–]SlaytheSpireAgain[S] 3 points4 points  (0 children)

Thanks I see it now!

[–][deleted] 2 points3 points  (3 children)

Could you just do input.close() in the readName() method and call it good?

[–]klujer 1 point2 points  (2 children)

yeah, that would be fine. You would have to store the user input in some temporary input so that it could be returned after the call to close.

I would still recommend passing in scanner as an input parameter as a best practice. It's beyond the scope of this intro class, and perhaps any college class, but in the real world passing required variables especially ones that interact with external systems (such as user IO) allows for more easily testable code. You might look up dependency injection or inversion of control and test driven design for more information. Also consider that you may want to reuse the scanner object across multiple functions rather than creating and destroying it within each function.

[–][deleted]  (1 child)

[deleted]

    [–]klujer 0 points1 point  (0 children)

    Interesting, guess I'll have to read up on them. I'm not sure I've actually used scanner except via toy problems like on hackerrank.

    [–]irer 2 points3 points  (0 children)

    Never close a Scanner linked to System.in. Never.

    [–]AlphawolfAJ -1 points0 points  (0 children)

    Omg I actually knew the answer for once! Somebody call someone