Sally Jenkins wrote:I would like to "check" if all characters entered are integers.
Good point, that the regexes have been validated by twelve years' regular use. If you get the text for the int with scanner1#next() and pass it to scanner2's constructor, that should reduce the risks of passing further input; it will be necessary however to change the delimiter if your input looks like this:-Mike Simmons wrote:. . . The regexes have already been written and debugged . . . and the exception handling is hidden from view, so . . . pretend it isn't there. The problem you noted about what if there's more input after the number . . .
Exception handling is a poor substitute for control structures; in the case of hasNextInt, there is only a risk of an exception (which is hidden from view) if the regex matches an integer and (probably) if it has ten digits. That is because the only range matched by a regex where one can be sure the text represents an integer and one is not sure whether the text represents an int is where there are ten digits. One can refine that by checking that the first digit is a 2.Rajdeep Biswas wrote:Regex is also a way, but thing the OP mentioned, I think the simplest way will be to do Integer.parseInt(). If exception is thrown, its not a number. If not, its cool! Thinking this functionality will go in some utility method, just handle the NumberFormatException and return boolean appropriately.
Sally Jenkins wrote:
To respond to some of the questions, I want to allow the user to enter a number, let's say 2356
Then I need a way to make sure that each character is a numerical character. In other words, I want an error message to appear should the user enter 23j5.
So, from what I understand, both Regex and parseInt are viable solutions.
The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory | www.TechAspire.blogspot.in
Sally Jenkins wrote:Then it appears that parseInt() might present a problem.
Another solution besides regex was that I can check each character of the string using if statements.
Is that an efficient approach? (see example below)
I forgot about that; I did know however that the format used by nextInt is different from integer literals in the code.Dave Tolls wrote:. . . '1,000' is a valid int in my locale.