int length = s.length();
if (length = 0){
return s;
}
else {
return s.charAt(0).toUpperCase()+ s.substring(1);
}
I get two errors saying:
if (length = 0){
^^^^^^^^^^
Type mismatch: cannot convert from int to boolean
return s.charAt(0).toUpperCase()+ s.substring(1);
^^^^^^^^^^^^^^^^^^^^^^^^^
Cannot invoke toUpperCase() on the primitive type char
Plus, if it's an empty sting it should just return it. That's why I'm using an If-Else statement.
if (length = 0)
should be if (length == 0)
You're assigning the value 0 to length
and not comparing it to 0.
I recommend you to take a look at this :
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
This way, your if
is never satisfied since the value inside it evaluated to the value of the assigned (0 in this case), so your program goes to the else
, and there you should:
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
In your if
statement, you are assigning the value 0
to length
. Because of this your compiler is complaining, because it expects a boolean
expression, and not an int in the if
statement (assignment returns the value it is assigning, which is why it mentions the int
).
You mean to be evaluating a boolean expression by using ==
instead.
The second issue is because charAt(int)
returns a char
primitive, which doesn't have any methods.
In this case you probably want to utilize Character.toUpperCase(char)
on the first character of your String
and appending the rest.
you're missing the ==
in the if statement
charAt(0)
returns a char, one way to make this a string is Character.toString(c)
Change it to this:
if (length == 0) {
return s;
}
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
Note: if the length of the string is exactly 1, you'll still get an error, because of s.substring(1)
. You might want to add an additional condition for when the length of the string is exactly 1.
This line:
if (length = 0) {
means " I want to set the length to zero ". But what you want is
if (length == 0) {
which means " Is the length equal to zero? "
The first statement eventually results into an exception as you're passing an integer into a place where boolean is expected.
Maybe you can try this:
String s = "testing";
String upper = s.toUpperCase();
System.out.print(upper);
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.