• 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
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

accepting input from only enter  RSS feed

 
Ranch Hand
Posts: 163
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: 9986
206
  • 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: 63791
209
  • 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?
 
My, my, aren't you a big fella. Here, have a tiny ad:
global solutions you can do in your home or backyard
https://coderanch.com/t/708587/global-solutions-home-backyard
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!