Reputation: 201
I want to force the user to input a number with 5 lengths long ( no more and no less) and store them inside an int variable, this includes a leading 0.
For example, the program should allow the user to input:
12345
04123
00012
But it should not work for:
123456
4123
001
I tried...
if(int x < 99999){
//continue with code
}
This would work only if the user input more than 5 lengths but it doesn't resolve the issue of the user putting in an int length less than 5
Upvotes: 0
Views: 2109
Reputation: 719
Something crazy simple like this. Lacks edge case handling (Read: Negative values)
boolean matchesLength(int n, int lengthLim){
char[] charArr = (n + "").toCharArray();
return (charArr.length == lengthLim);
}
Upvotes: 0
Reputation: 24691
Two functions. First, to verify the input:
static boolean is_valid_number(String x) {
// returns true if the input is valid; false otherwise
if(x.length != 5 || Integer.valueOf(x) > 99999) {
// Check that both:
// - input is exactly 5 characters long
// - input, when converted to an integer, is less than 99999
// if either of these are not true, return false
return false;
}
// otherwise, return true
return true;
}
and second, to get user input:
static int get_user_input() {
// Create a scanner to read user input from the console
Scanner scanner = new Scanner(System.in);
String num = "";
do {
// Continuously ask the user to input a number
System.out.println("Input a number:");
num = scanner.next();
// and continue doing so as long as the number they give isn't valid
} while (!is_valid_number(num));
return Integer.valueOf(num);
You might also have to do some error-handling, in case the given input isn't an integer at all. You could implement is_valid_number()
concisely like this:
static boolean is_valid_number(String x) {
try {
return (x.length == 5 && Integer.valueOf(x) <= 99999);
} catch (NumberFormatException e) {
// Integer.valueOf(x) throws this when the string can't be converted to an integer
return false;
}
}
Upvotes: 0
Reputation: 58
I think you should take input in string not in int then if the validation goes right you can parse it into integer like the following:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
/// take input
String userInput = "";
Scanner sc = new Scanner(System.in);
userInput = sc.nextLine();
int input ;
// validation test
if(userInput.length() == 5) {
input = Integer.parseInt(userInput);
}else {
// you can display an error message to user telling him that he should enter 5 numbers!
}
}
}
but you have to know that after parsing it into int if there's a leading zeros it could be gone.
Upvotes: 1