Reputation: 57
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.
Upvotes: 3
Views: 259
Reputation: 4006
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;
}
Upvotes: 0
Reputation: 201447
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)
Upvotes: 3
Reputation: 1243
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.
Upvotes: 0
Reputation: 11284
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);
Upvotes: 3