Checking for invalid character input | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Checking for invalid character input

assuming that I'm using the lines: Scanner scan = new Scanner(); char x; x = scan.next(".").charAt(0); To capture character inputs, how do I check for when the user just hits the enter key or enters a special character? Characters are primitives so I can't dereference them using string elements, right? Any thoughts on the matter?

26th May 2017, 3:24 AM
Steven Schneider
Steven Schneider - avatar
4 Answers
+ 12
Since if those special characters have representations (\n, \t) I'd take a look at the ASCII data on the characters you want to disallow.... Also see what char manipulations might be out there in the libraries. In C++ there's a hacky workaround, but I bet there's a reasonable way to do it.... I just don't know the details. Hope this at least gives you done things to explore!
26th May 2017, 3:44 AM
Jim
Jim - avatar
+ 12
Hmm, could that be because the return triggers the scanner? That'd leave you with a \0.. What about checking if the chart is something standard [A-Za-z0-9], turning the problem around. You could add punctuation, just member to escape appropriately. If you're after discriminating among types of special characters, then you might have to delve into recasting the char and checking the ascii value directly (which does seem to be possible from a quick look).
26th May 2017, 4:25 AM
Jim
Jim - avatar
+ 3
@Jim Hrm, that has me wondering, your comment about turning the problem around. Perhaps I've got it backwards altogether. I'll need to think about this.
27th May 2017, 2:37 AM
Steven Schneider
Steven Schneider - avatar
+ 2
I've already tried using "if (x != '\n')". Everything compiles without error, but it doesn't prevent the program from hanging when the user just hits the enter key. I have code that should fire if the condition works and is true, but it doesn't fire. This leads me to think that the the condition doesn't work or isn't true. So I'll probably be reading Oracle's documents for enlightenment. Your input is appreciated, @Jim.
26th May 2017, 4:05 AM
Steven Schneider
Steven Schneider - avatar