One of my problem sets requires me to take create a subroutine that will take a String variable as a parameter and return that same string except with the first letter of each word capitalized. The examples in the text use non-standard class the Professor specifically designed. I don't want to do this as I would think it makes more sense to learn with standard classes than see what else is out there. The problem I am having though is my subroutine is returning a String in all capitals. Here is my code:
import java.util.Scanner;
public class Capitalize {
static String capitalizeString(String x) {
String completedConversion = "";
for (int i=0; i < x.length(); i++) {
if (i == 0) {
char ch = x.charAt(i);
ch = Character.toUpperCase(ch);
completedConversion = completedConversion + ch;
i++;
}
if (Character.isLetter(i - 1)) {
char ch = x.charAt(i);
completedConversion = completedConversion + ch;
}
else {
char ch = x.charAt(i);
ch = Character.toUpperCase(ch);
completedConversion = completedConversion + ch;
}
}
return completedConversion;
} // End of subroutine
I have not yet added any commenting etc. but it should be pretty straightforward.
SOLVED: Using Keammoort's answer
public class Capitalize {
static String capitalizeString(String x) {
String completedConversion = "";
for (int i=0; i < x.length(); i++) {
if (i == 0) {
char ch = x.charAt(i);
ch = Character.toUpperCase(ch);
completedConversion = completedConversion + ch;
}
else if (!Character.isWhitespace(x.charAt(i - 1))) {
char ch = x.charAt(i);
completedConversion = completedConversion + ch;
}
else {
char ch = x.charAt(i);
ch = Character.toUpperCase(ch);
completedConversion = completedConversion + ch;
}
}
return completedConversion;