• Post Reply Bookmark Topic Watch Topic
  • New Topic

How do I stop reading input?  RSS feed

 
Billy Sang
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Is there a way to terminate input without having to press ctr-z? After it reads all lines in a file it keeps on expecting to read a next line of input. How can I make it stop?
I don't get it. Isn't this the purpose of the hasNext* methods?
 
Joe Areeda
Ranch Hand
Posts: 334
2
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Billie,

The answer to your question has to do with how character devices like the console are treated as files.

The ^Z signals the reader that the "end of file" has been reached and there's no more input.

Imaging your program is asking the user to enter I don't know say "today's receipts". He types in 10 values goes to lunch comes back types in 10 more. How can we determine he's done?

The way it's usually done is he has to somehow explicitly specify there's no more. ^Z is a ...well... pretty geeky way to do it. Your program could also ask him to type in the word end, or treat a blank line as the end or ask him to enter Kalamazoo.

Another way that I would strongly discourage is to ask them to first enter in the number of numbers they are going add. I've found that causes more trouble than it's worth in most cases.

If you go the non standard way then you have to read strings not integers and see if it's a number or the magic stop word.

Joe
 
Billy Sang
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I wanted to go the non-standard route and have the file close itself automatically after reading the entire file. In C/C++, I know you can use EOF, but I don't get why Java doesn't have something as similar and elegant then C/C++.
 
Billy Sang
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, and by the way, those hasNextInt() are really supposed to be hasNextLine(). It was just for testing purposes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!