-1

Here is my code:

private String studentId;

    public void setStudentId(String studentId) {

        if (studentId != null && studentId.trim().length() > 0 && studentId != " ") {
            if (studentId.charAt(0) = 'a') {
                this.name = studentId;
            }
        } else {
            System.out.println("Error. Not Valid.");
        }
    }

I'm getting this error:

"Unexpected type, required : variable, found : value".

I'm supposed to make sure if the first letter of the the passed String is equal to 'A' or not. If anyone can help me to fix this, I would appreciate it.

Also, if there are any other mistakes in my code I would be happy to be informed.

skomisa
  • 16,436
  • 7
  • 61
  • 102
  • Try == instead of = in the if. – Isaiah Mar 21 '19 at 03:28
  • 1
    Also String comparisons are done using the `.equals()` method and not this `studentId != " "`. This tests object equality and not the actual String content equality. – akortex Mar 21 '19 at 03:31
  • Also, it's really unnecesary to constantly check balues for null. Most values will not be, and it is safe NOT to check because one expects the methods to be properly used in the first place. – Isaiah Mar 21 '19 at 03:38
  • 2
    `if (studentId != null && studentId.startsWith("a"))` – Kartik Mar 21 '19 at 04:16

3 Answers3

0

Two things,

first, studentId != null && studentId.trim().length() > 0 is enough, studentId != " " is not necessary. Because studentId.trim() would do the favor.

second,

studentId.charAt(0) = 'a' is an assignment, not an expression

should be

'a' == studentId.charAt(0)

Bejond
  • 1,188
  • 1
  • 11
  • 18
0
private String studentId;

public void setStudentId(String studentId){


if(studentId != null && studentId.trim().length() > 0 && studentId != " " ){
    if(studentId.charAt(0) == 'a'){
        this.name = studentId;
}
}
else{
    System.out.println("Error. NOt Valid.");
}

}

Terchila Marian
  • 2,225
  • 3
  • 25
  • 48
0

this.name -- here name is not defined, it should be studentId, use the following snippet

  public void setStudentId(String studentId) {

    if (null != studentId &&
        studentId.trim().length() > 0 &&
        'a' == studentId.charAt(0) = 'a') {
         this.studentId = studentId;
    } else {
        System.out.println("Error. Not Valid.");
    }
}
Tanmoy Bhattacharjee
  • 1,040
  • 11
  • 21