Reputation:
What am I doing wrong? When I run my program it only prints some of my string, and it does not capitalize the first letter..
public class StringTraining extends ConsoleProgram {
public void run() {
String str = "halOOlOO";
capitalize(str);
}
private String capitalize(String str){
String s = "";
char ch;
for(int i = 0;i<str.length();i++) {
ch = str.charAt(i);
if(i==0 && Character.isLowerCase(ch)) {
Character.toUpperCase(ch);
s += ch;
i++;
} else {
Character.toLowerCase(ch);
s += ch;
i++;
}
}
println(s);
return s;
}
}
Upvotes: 1
Views: 101
Reputation: 4216
Change your capitalize(String str) method like this -
private static String capitalize(String str) {
char[] chars = str.toCharArray();
String caps = chars[0]+"";
caps = caps.toUpperCase();
String output = caps;
for(int i=1;i<chars.length;i++) {
output = output + chars[i];
}
return output;
}
Output :
HalOOlOO
Upvotes: 0
Reputation: 370
Remove some unnecessary codes from your capitalize(String)
method such as i++
and use
s += String.valueOf(Character.toUpperCase(ch));
code instead of
Character.toUpperCase(ch);
s += ch;
Complete capitalize(String) method
private static String capitalize(String str) {
String s = "";
char ch;
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (i == 0 && Character.isLowerCase(ch)) {
s += String.valueOf(Character.toUpperCase(ch));
} else {
s += String.valueOf(Character.toLowerCase(ch));
}
}
println(s);
return s;
}
Upvotes: 2
Reputation: 2777
You need to assign the variable ch to the upper or lower case value:
for(int i = 0;i<str.length();i++) {
ch = str.charAt(i);
if(i==0 && Character.isLowerCase(ch)) {
ch = Character.toUpperCase(ch);
s += ch;
} else {
ch = Character.toLowerCase(ch);
s += ch;
}
}
Upvotes: 4
Reputation: 19
toLowerCase() return a string, you need to assign it to ch
.
You also need to increment your i
only one time (in the for
, and not in the if
)
Upvotes: 1
Reputation: 21965
You should not increment i
again in the loop since it will be done automatically in the signature of the loop.
You have to assign Character.toUpperCase(ch)
to the String
or append it.
I'd suggest you use a StringBuilder
when looping to build a String object
Correction
private static String capitalize(String str){
StringBuilder s = new StringBuilder();
char ch;
for(int i = 0;i<str.length();i++) {
ch = str.charAt(i);
if(i==0 && Character.isLowerCase(ch)) {
s.append(Character.toUpperCase(ch));
} else {
s.append(Character.toLowerCase(ch));
}
}
return s.toString();
}
Output
Halooloo
Upvotes: 4