Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use enf of file character in Scanner

 
ramya narayanan
Ranch Hand
Posts: 338
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm using scanner to fetch input from inputstream(System.in)
The challenge is:
1) After printing the values , the connection to inputstream is not closed i.e it is ready to accept input values from System.in when it is not needed, atleast in my case.
2) So how to make the scanner find the end of file from the input stream.




I want to know is there any way
1) to find the length of the input stream values we give.

2) Can we impose restrictions on the number of values scanner can parse in Scanner or in inputstream on number of values we can give.

When I try finding out EOF through usage of -1 like this


But the problem with this approach
1) It doesn't display all the values I enter through System.in
2) Old problem of non-return of control persists
If someone could throw some light on this, I would appreciate it.
Regards.
 
shan raj
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think in your case to skip reading the input from user you can use break; to come outof loop if you don't need. Also better to use sc.close() instead of System.in.close().
 
ramya narayanan
Ranch Hand
Posts: 338
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I think in your case to skip reading the input from user you can use break; to come outof loop if you don't need.

On what condition, i can give break.
If i know exactly the number of values the user should give, then it is possible
But if I want the application to be dynamic, the user can give varied no of values each time he runs it.
In that case what can we do.

Also better to use sc.close() instead of System.in.close().

If I use sc.close() in that place instead of System.in.close() it throws java.lang.IllegalStateException.
By the way why we should not close the inputstream.
Regards.
 
Campbell Ritchie
Sheriff
Posts: 48433
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would do well to read the Scanner API documentation, and see what those methods do and what those methods return. If you get the bit with ==-1 in to compile, I shall be very surprised!
 
Campbell Ritchie
Sheriff
Posts: 48433
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And, as far as I know, you only get an end-of-file character of -1 if you use an unbufferred Reader. Scanner does all the buffering, so it doesn't return -1 for end-of-file.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic