3
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);    

Im trying to make card be 10 characters long. Like (1234567890), and if the user inputs (123) or (123456789098723) an error message should appear. card.length doesnt seem to work.

  • maybe you could try to receive plain string first, then parse it to integer. – Jason Hu Dec 02 '14 at 02:23
  • 1
    I endorse the "treat the card number as a string" approach - In general card numbers do not require mathematical operations to be performed on them, adn can contain leading zeros so using a String is actually a sensible representation. – Matt Coubrough Dec 02 '14 at 02:27

4 Answers4

3

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);
Pham Trung
  • 11,204
  • 2
  • 24
  • 43
3

You could change

if(card.length != 10){

to something like

if(Integer.toString(card).length() != 10){

Of course, it's possible the user entered

0000000001

which would be the same as 1. You could try

String card = input.next(); // <-- as a String

then

if (card.length() == 10)

and finally

Integer.parseInt(card)
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

In Java, you cannot get the length of an int. The easiest way to find the number of digits is to convert it to a String. However, you can also do some math to find out the number's length. You can find more information here.

Community
  • 1
  • 1
Greg
  • 1,225
  • 3
  • 16
  • 35
0

You cannot get the length of an int. It would be much better to get input as a String, and convert it into an int later on, if the need arises. You can do the error checking in your while loop, and if you like short circuiting, you can have the while check display your error message too:

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 have your errorMessage function return true, and display the error messages:

private boolean errorMessage()
{
    out.println("The number you typed is incorrect");
    out.println("The number must be 10 numbers long");
    return true;
}
Shadow
  • 3,926
  • 5
  • 20
  • 41