Search code examples
javastringvariable-length

How to parse a string?


So I'm trying to get the user to enter text into a text box and my program will tell the user how many letters the word contains. I initialized the variable String1 (String String1;) to be the word the user entered. Now the part I'm confused about is that when I try to set the label for the answer to display the answer I get the error

int cannot be converted to string.

Here's the part of the code I'm stuck on:

String String1;

String1 = txtlength.getText();


lblLengthAnswer.setText (String1.length());

Solution

  • Apparently the setText() method accepts only Strings (I'm not completely sure, because you only pasted part of the code, but I'm pretty sure). On the other hand String#length() gives you an int value. You can't pass int to a method which requires a String, hence the error. To call it java would need to convert an int to String, which it doesn't do. Convert the int to String by hand, by calling String.valueOf. And please start variable names with lowercase.