0

I am trying to limit a users input for their student ID to a length of 8 characters but when I use input.length() it tells me I cannot invoke length() on a primitive type int. Is there any way I can easily fix/achieve what I desire another way? The error occurs on the fourth line.

input.nextLine();
System.out.print("Please enter your Student ID:  "); //Prompts for Student ID
int studentId = input.nextInt();
if(studentId.length() != 8)
    {
       System.out.println("Student ID must be 8 characters");
    }
Cian
  • 1
  • 2

2 Answers2

0

you could use a simple function like this for validation

bool validId(int n) {
    if (n < 10) return 1;
    int length = 1 + numDigits(n / 10);
    if (length == 8) return true;
    else return false;
}

Hope that helps

it also abstracts that out making it easier to read :)

sjdm
  • 591
  • 4
  • 10
0

You defined studentId to be an Integer, and thus does won't have a length() method.

You could cast the studentId variable to a String and then use the length() method.

String student_id_as_string = studentId + "";
if (student_id_as_string.length() != 8) { 
  ... 
}
bkupfer
  • 124
  • 11