简体   繁体   中英

I keep getting this error int cannot be dereferenced

The code is supposed to return the first and the last letter of a string ,but I keep getting these errors Line 5: int cannot be dereferenced and Line 6: int cannot be dereferenced

public String firstAndLast(String str)
  {
  int length = str.length();
  char first= length.charAt(0);
  char last= length.charAt(length - 1);
  return String.valueOf(first) + String.valueOf(last); 
  }

Not

char last= length.charAt(length - 1);

but

char last= str.charAt(length - 1);

More important, the error message is telling you exactly where your problem is -- which line, and what's wrong -- you're trying to call a method on length, an int. In the future, read the error messages critically as they'll usually give you the problem and a solution can be obvious once you understand the problem.

length is a primitive type int variable. You can not invoke methods through it, maybe the code would be in this way?

    public String firstAndLast(String str)
    {
        int length = str.length();
        char first= str.charAt(0);
        char last= str.charAt(length - 1);
        return String.valueOf(first) + String.valueOf(last); 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM