This week's book giveaway is in the XML and Related Technologies forum.
We're giving away four copies of Java XML & JSON and have Jeff Friesen on-line!
See this thread for details.
Win a copy of Java XML & JSON this week in the XML and Related Technologies forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

accepting input from only enter  RSS feed

 
Ranch Hand
Posts: 64
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have noticed that a blank line appears after pressing enter (with no input)
is there a way i can have my scanner accept a blank line as invalid input?

 
Saloon Keeper
Posts: 9703
192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean, have the scanner reject a blank line? From the command line?

There's no way to prevent the blank line appearing in the command line window. A Java application can not control this behavior. However, if a user enters a blank line, you can just treat the line (which would be an empty string) as invalid input the same way you would treat other invalid input.
 
Marshal
Posts: 62801
203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you retain the default delimiter, that is only a problem if you use the findInLine() (beware: overloaded) or nextLine() methods. If you use nextInt() or similar, the line end sequences count as part of the delimiter, so the Scanner object ignores them.
Didn't I show you a utility class on Friday? Remember that System.in should remain open for ever, so it always has a next line implicitly.You cna insert a method like this:-Java11+ users may prefer to use the strip() method rather than trim().
And why didn't I use System.out.printf on Friday?
 
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!