2

When I type this code in it brings up an error saying

"cannot find symbol length"

All I am trying to do is find the length of the string and store that length into a variable.

Can anyone help me find the problem?

String[] words = {
    "hello", "java", "yamaha", "dell", "hydro"
};

a = (int) (Math.random() * 6);
b = (words[a]).length;
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Jared27
  • 23
  • 1
  • 1
  • 5

3 Answers3

3

String class doesn't have a length property, you need to call length() method

 b = (words[a]).length();
       /\
       ||
       ||
       ||
     Since you are accessing the a'th index of array, which returns String hence you have to call length() method instead of length which is the field in array instead

As Scarywombat pointed out you might get Out Of Bounds exception as well, so you need to change your condition

a = (int) (Math.random() * 5); // 5 instead of 6
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

String doesn't support length variable , length variable is used for other array , instead use length() method.

 String[] words =
{
    "hello", "java", "yamaha", "dell", "hydro"
};



a = (int) (Math.random() * 6);
b = (words[a]).length();
Minion
  • 964
  • 14
  • 16
  • Is `a = (int) (Math.random() * 6);` correct? – Scary Wombat Nov 29 '17 at 05:16
  • yes.. i think there is no need to cast to int @Scary Wombet – Minion Nov 29 '17 at 05:23
  • 1
    @PrakashSharma he isn't talking about casting, you have to cast definitely. The problem is that this statement can give a index 5 which will cause out of bounds exception, Since our array's length is 5 – Neeraj Jain Nov 29 '17 at 05:29
  • @NeerajJain But to be fair current question is about compilation error and this post answers it. Problem shown in comments is answer for OP's next question where index will be out of bounds (sometimes). If that is the reason someone down-voted then I can't really agree with it. – Pshemo Nov 29 '17 at 05:43
  • @Pshemo firstly I didn't downvote. I was just helping Prakash to understand what Scary wombat is saying :) – Neeraj Jain Nov 29 '17 at 05:50
  • @NeerajJain I never said you did :) Was just pointing out to others who may see that `-1` score that this down-vote may not be well deserved. Sometimes when people see negatively scored answer they thing/[act] like: "there needs to be something wrong with this answer... [read comments]... oh that is what is wrong [adds another down-vote]". I simply wanted to prevent it which is why my comment was `@linked` to yours. – Pshemo Nov 29 '17 at 06:03
-1

String doesn't have length property whereas array has it. We need to use length() for strings and length for Arrays.

Bhavani
  • 195
  • 1
  • 10