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.

+3


source to share


4 answers


Just change int to String

   String card = input.next();
   if(card.length() != 10){
      //Do something
   }

      



You can easily convert it to int later

   int value = Integer.parseInt(card);

      

+3


source


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)

      

+3


source


In Java, you cannot get length

int

. The easiest way to find the number of digits is to convert it to String

. However, you can also do some math to find out the length of the number. You can find more information here .

0


source


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;
}

      

0


source







All Articles