I need an example of a Boolean expression in Java that will only accept numbers
ID: 3558533 • Letter: I
Question
I need an example of a Boolean expression in Java that will only accept numbers between 10 and 100 and if a letter or symbol is provided, a response "you have entered a non-digit" will display.
(This is part of a homework assignment that has four exceptions and I tried creating another exception for non digits, but I couldn't get the response above to display properly. So I thought I could add a Boolean expression to make only numbers true. I was just going to add the Boolean to the main program I will run. If anyone has a better idea on how to add this, I would greatly appreciate it)
Explanation / Answer
A boolean expression for the number check might be:
(number >= 10) && (number <= 100)
--
For the second part, if would use try / catch detect invalid input. Let's say you're using a Scanner to read the input:
try {
... int number = scanner.nextInt();
... boolean valid = (number >= 10) && (number <= 100);
... if (valid) {
... ... process the input
... } else {
... ... handle the error ...
... }
catch (NumberFormatException e) {
... System.out.println ("Non digit or invalid number format entered");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.