Method not recognizing PAREN when looping through character array

C

Curts

Can anyone take a look at the code below? I have this method that is
supposed to return a string with only the first character of a word
uppercase. This is working fine except for a string with parens in
it.

public class paren {

public static String s = "STRING THAT (HAS PARENS) INSIDE OF IT.";

public paren() {
System.out.println("Before UCW: " + s);
System.out.println(" After UCW: " + this.ucwords(s));
}

public String ucwords(String str) {
char[] broken = str.toLowerCase().toCharArray();
StringBuffer buf = new StringBuffer();

boolean doUpperCase = true;

for (int i = 0; i < broken.length; i++) {

if (doUpperCase) {
buf.append(String.valueOf(broken).toUpperCase());
doUpperCase = false;
} else {

//if (broken == '(') <-- this doesn't work
if (String.valueOf(broken).equals("(")) // <--
doesn't work either
doUpperCase = true;
else if (broken == ' ')
doUpperCase = true;
buf.append(broken);
}
}

return buf.toString();
}

public static void main(String[] args) {
new paren();
}
}

Any ideas on what I might be doing wrong?

Cheers,
Curts
 
L

Lee Fesperman

Curts said:
Can anyone take a look at the code below? I have this method that is
supposed to return a string with only the first character of a word
uppercase. This is working fine except for a string with parens in
it.

public class paren {

public static String s = "STRING THAT (HAS PARENS) INSIDE OF IT.";

public paren() {
System.out.println("Before UCW: " + s);
System.out.println(" After UCW: " + this.ucwords(s));
}

public String ucwords(String str) {
char[] broken = str.toLowerCase().toCharArray();
StringBuffer buf = new StringBuffer();

boolean doUpperCase = true;

for (int i = 0; i < broken.length; i++) {

if (doUpperCase) {
buf.append(String.valueOf(broken).toUpperCase());
doUpperCase = false;
} else {

//if (broken == '(') <-- this doesn't work
if (String.valueOf(broken).equals("(")) // <--
doesn't work either
doUpperCase = true;
else if (broken == ' ')
doUpperCase = true;
buf.append(broken);
}
}

return buf.toString();
}

public static void main(String[] args) {
new paren();
}
}

Any ideas on what I might be doing wrong?


Sure, you shouldn't be checking the doUpperCase flag before you check for '(' or ' '.
The space before the left parenthesis in the text sets doUpperCase to true, so you do a
toUpperCase() on the parenthesis.

Your algorithm is not very general. Homework?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top