How can I set limits on the number of characters that can be entered? (Java)
do{
out.println("\n---------------------------------");
out.println("---------------------------------");
out.print("Please type your acces card number: ");
try{
card = input.nextInt();
if(card.length != 10){
out.println("The number you typed is incorrect");
out.println("The number must be 10 numbers long");
continue;
}
}
catch(InputMismatchException ex){
}
}while(true);
I am trying to make a map 10 characters long. For example, (1234567890) and if the user enters (123) or (123456789098723), an error message should appear. card.length doesn't work.
source to share
You can change
if(card.length != 10){
to something like
if(Integer.toString(card).length() != 10){
It is of course possible that the user has entered
0000000001
which will be the same as 1
. You may try
String card = input.next(); // <-- as a String
then
if (card.length() == 10)
and finally
Integer.parseInt(card)
source to share
You cannot get the length int
. It would be much better to receive the input as String
well as convert it to int later if the need arises. You can do error checking in your while loop and if you like short-circuiting you can also check if your error message is displayed:
out.println("\n---------------------------------");
out.println("---------------------------------");
out.print("Please type your access card number: ");
do {
try {
card = input.nextLine();
} catch (InputMismatchException ex) {
continue;
}
} while ( card.length() != 10 && errorMessage());
And let your function errorMessage
return true and display error messages:
private boolean errorMessage()
{
out.println("The number you typed is incorrect");
out.println("The number must be 10 numbers long");
return true;
}
source to share