PDA

View Full Version : Capitalize Java string?




MBP123
Oct 14, 2007, 09:04 PM
So if I ask the user to Input data;

String s1 = JOptionPane.showInputDialog("Type in a sentence. ");

how would i then convert that input to capitalize the first letter of each word? For example, if they typed in,

"this JavA is maKing me gO cRazy"

and I need the system.out.println to be "This Java Is Making Me Go Crazy"

How would I go about that? Im going nuts here!!!

Thanks



sord
Oct 14, 2007, 09:41 PM
Please read about the Java String API.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

You have asked many questions here that can be easily answered, so please start giving direct questions to what you don't understand, we will NOT do your homework for you.

MBP123
Oct 14, 2007, 10:26 PM
I am definitely not asking for people to do my homework for me. I like figuring these things out myself, and get a lot of satisfaction from it, but I do not know what I am looking at on that site. Ive spent a good deal of time on it, and it just overwhelms me a little bit.

I know I have to start it as

public class asgn3 {
public static void main( String[] args ) {
String s1 = JOptionPane.showInputDialog("Type in a sentence. ");

Then I found this ......

http://www.cs.princeton.edu/introcs/31datatype/Capitalize.java

which seems to be what I am looking for, but I do not know what StdIn.readLine is.

I am assuming I have to substitute my s1 from the above code for that somehow but am not really sure how to go about doing that.

MBP123
Oct 14, 2007, 10:27 PM
I am definitely not asking for people to do my homework for me. I like figuring these things out myself, and get a lot of satisfaction from it, but I do not know what I am looking at on that site. Ive spent a good deal of time on it, and it just overwhelms me a little bit.

I know I have to start it as

public class asgn3 {
public static void main( String[] args ) {
String s1 = JOptionPane.showInputDialog("Type in a sentence. ");

Then I found this ......

http://www.cs.princeton.edu/introcs/31datatype/Capitalize.java

which seems to be what I am looking for, but I do not know what StdIn.readLine is.

I am assuming I have to substitute my s1 from the above code for that somehow but am not really sure how to go about doing that.

sord
Oct 14, 2007, 10:32 PM
This splits the input (that you may have received from any way you want) into arrays with spaces as the delimeter
String[] words = line.split("\\s");
Then as they are iterating, they are doing this:
if (s.length() == 0) return s;
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
Which means if our current string is of length 0, don't bother continuing. Then return the first letter uppercased, with the following letters lowercased.

Instead of using their standard out, you can use a StringBuffer and append the results, then output that once done with whatever fashion you want.

MBP123
Oct 14, 2007, 10:34 PM
I also found this on the website

capitalize

public static java.lang.String capitalize(java.lang.String s)
Capitalizes a string.

Parameters:
s - The string
Returns:
The capitalized string


But where would this go on the code? After

import javax.swing.JOptionPane;

public class asgn3{
public static void main( String[] args ) {
String s1 = JOptionPane.showInputDialog("Type in a sentence. ");


?

MBP123
Oct 14, 2007, 10:36 PM
This splits the input (that you may have received from any way you want) into arrays with spaces as the delimeter
String[] words = line.split("\\s");
Then as they are iterating, they are doing this:
if (s.length() == 0) return s;
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
Which means if our current string is of length 0, don't bother continuing. Then return the first letter uppercased, with the following letters lowercased.

Instead of using their standard out, you can use a StringBuffer and append the results, then output that once done with whatever fashion you want.

We havent gotten in to arrays or delimeters yet, so what you are saying is kind of going right over my head. I am really sorry and not trying to be a pest or anything, but is there a more basic way of doing this?

sord
Oct 14, 2007, 10:40 PM
In that case, you could use a for loop to the length of your string. Keep a boolean to determine if the last character was a space. Then if the last character was a space, append to a string buffer the capital letter of your current letter, otherwise the lower case. If you receive a space, set the boolean to true.

Use charAt to get the character at the position you are at during your iteration. I would probably use a StringBuffer to keep track of your results, calling append with your new characters, however if you haven't learned about StringBuffer then just use String concatination (+). Once you are done, output your new string.

Understand?

sord
Oct 14, 2007, 10:41 PM
I also found this on the website

capitalize

public static java.lang.String capitalize(java.lang.String s)
Capitalizes a string.

Parameters:
s - The string
Returns:
The capitalized string


But where would this go on the code? After

import javax.swing.JOptionPane;

public class asgn3{
public static void main( String[] args ) {
String s1 = JOptionPane.showInputDialog("Type in a sentence. ");


?
If you used that, you would use capitalize with your s1, then output its result.

MBP123
Oct 14, 2007, 10:59 PM
In that case, you could use a for loop to the length of your string. Keep a boolean to determine if the last character was a space. Then if the last character was a space, append to a string buffer the capital letter of your current letter, otherwise the lower case. If you receive a space, set the boolean to true.

Use charAt to get the character at the position you are at during your iteration. I would probably use a StringBuffer to keep track of your results, calling append with your new characters, however if you haven't learned about StringBuffer then just use String concatination (+). Once you are done, output your new string.

Understand?

I hate to say it, but I really do not understand that much. I do not know what a string buffer is.

If you could show me some basic code to illustrate your point, it would probably help. My professor posted this example of how to convert a word of capital letters to that of lowercase. Maybe this well show you exactly what level I am on and how she probably wants it structured to some degree.

Sorry for being dense.


// String2: what is the output?
import javax.swing.JOptionPane;
public class String2 {
public static void main( String[] args ) {
String s1 = JOptionPane.showInputDialog("Type a word in capital letters: ");
int length = s1.length();
int counter = 0;
char NextLetter;
System.out.println("You entered: " + s1);
while (counter < length) {
NextLetter = s1.charAt(counter);
NextLetter += 32;
System.out.print(NextLetter);
counter++;
}
System.out.print("\n");
System.exit( 0 );
} // end main
} // end of program

SC68Cal
Oct 14, 2007, 11:34 PM
That example sucks so hard it's not funny. What happens if you put in lower case letters and numbers? Seriously, your professor needs to go back to school.

Bugs I see right away:

1) It's written in a main method, which means it's totally useless to other programs.
2) These kinds of programs should be written as static methods that accept strings of input passed to them, and they should return strings. Anything less is totally useless.
2) Unless you put capital letters in, it won't do what it's supposed to. Put a few numbers in and see what happens.

I had to write a method to take user input and filter out all the the stuff that I didn't want, keeping only letters (that are changed to lower case) and single spaces between words. I wanted to use it later, so I made sure to save it to a string to pass back rather than printing it to the console.


//
// strip.java
// Lab4
//
// Created by Sean Collins on 9/18/07.
// Copyright 2007 Sean Collins. All rights reserved.
//

public class strip {

public static String stripChars(String a){
a = a.trim();
String b = ""; int x;
for (int i=0; i < a.length(); i++){
if( a.codePointAt(i) >= 97 && a.codePointAt(i) < 123){
b = b + a.charAt(i);
} else if(a.codePointAt(i) >= 65 && a.codePointAt(i) < 90){
x = a.charAt(i);
x = x + 32; // add 32 to ascii value to switch to lower case
b = b +((char)x); //typecast and toss into new string
}
if(a.codePointAt(i) == 32 && a.codePointAt(i+1) !=32){
b = b + a.charAt(i);
}
}
return b;
}
}

Persifleur
Oct 15, 2007, 05:31 AM
That example sucks so hard it's not funny. What happens if you put in lower case letters and numbers? Seriously, your professor needs to go back to school.
It works properly if you follow the given instructions i.e. "Type a word in capital letters". No spaces, no numbers, no lower-case letters. It's meant to be a starting point, not half the answer. While your suggestions are all valid, one would probably wish to limit code complexity when trying to teach concepts. Help see the wood for the trees so to speak. This is obviously a first year student just starting to program, and your rather opaque example with non-descriptive variable names and magic numbers will only confuse him.

To the OP, take the instructor's code as a starting point. First, make sure you understand what it does. If you don't understand it, talk to your instructor and have her explain it to you. Once you understand what it's doing, take a look at the Character class. There are several static methods which you should concentrate on: Character.toLowerCase(), Character.toUpperCase(), and Character.isWhiteSpace().

lazydog
Oct 15, 2007, 06:25 AM
That example sucks so hard it's not funny. What happens if you put in lower case letters and numbers? Seriously, your professor needs to go back to school.

Bugs I see right away:

1) It's written in a main method, which means it's totally useless to other programs.
2) These kinds of programs should be written as static methods that accept strings of input passed to them, and they should return strings. Anything less is totally useless.
2) Unless you put capital letters in, it won't do what it's supposed to. Put a few numbers in and see what happens.

I had to write a method to take user input and filter out all the the stuff that I didn't want, keeping only letters (that are changed to lower case) and single spaces between words. I wanted to use it later, so I made sure to save it to a string to pass back rather than printing it to the console.


//
// strip.java
// Lab4
//
// Created by Sean Collins on 9/18/07.
// Copyright 2007 Sean Collins. All rights reserved.
//

public class strip {

public static String stripChars(String a){
a = a.trim();
String b = ""; int x;
for (int i=0; i < a.length(); i++){
if( a.codePointAt(i) >= 97 && a.codePointAt(i) < 123){
b = b + a.charAt(i);
} else if(a.codePointAt(i) >= 65 && a.codePointAt(i) < 90){
x = a.charAt(i);
x = x + 32; // add 32 to ascii value to switch to lower case
b = b +((char)x); //typecast and toss into new string
}
if(a.codePointAt(i) == 32 && a.codePointAt(i+1) !=32){
b = b + a.charAt(i);
}
}
return b;
}
}

If I'm not mistaken you have a couple of bugs in your code.

b e n

toddburch
Oct 15, 2007, 06:45 AM
} else if(a.codePointAt(i) >= 65 && a.codePointAt(i) < 90){

This is why I would never use the non-human representation of a character in source code.


if(a.codePointAt(i) == 32 && a.codePointAt(i+1) !=32){


Can you say "out of range"?

Todd

MBP123
Oct 15, 2007, 07:38 AM
Alright guys I know you know more about java than I do. Could someone please help me out, explaining in very basic terms, with examples of code for me in regards to the original question?

Thanks

toddburch
Oct 15, 2007, 07:49 AM
AIM me and I'll walk you through your instructor's example.

Todd

lazydog
Oct 15, 2007, 07:52 AM
Okay, you could do something like this:-

1) Take the input string and convert it to an array of words. Have a look at using the split() method in String.
2) Loop through your array of words and capitalise the first letter of each word. Use the toUpperCase() and substring() methods of String.
3) Finally, concatenate your array of words together for the final value.

Lots of ways of doing it… not saying the above is the best.

b e n

gnasher729
Oct 15, 2007, 08:23 AM
That example sucks so hard it's not funny. What happens if you put in lower case letters and numbers? Seriously, your professor needs to go back to school.

Bugs I see right away:

1) It's written in a main method, which means it's totally useless to other programs.
2) These kinds of programs should be written as static methods that accept strings of input passed to them, and they should return strings. Anything less is totally useless.
2) Unless you put capital letters in, it won't do what it's supposed to. Put a few numbers in and see what happens.

I had to write a method to take user input and filter out all the the stuff that I didn't want, keeping only letters (that are changed to lower case) and single spaces between words. I wanted to use it later, so I made sure to save it to a string to pass back rather than printing it to the console.


//
// strip.java
// Lab4
//
// Created by Sean Collins on 9/18/07.
// Copyright 2007 Sean Collins. All rights reserved.
//

public class strip {

public static String stripChars(String a){
a = a.trim();
String b = ""; int x;
for (int i=0; i < a.length(); i++){
if( a.codePointAt(i) >= 97 && a.codePointAt(i) < 123){
b = b + a.charAt(i);
} else if(a.codePointAt(i) >= 65 && a.codePointAt(i) < 90){
x = a.charAt(i);
x = x + 32; // add 32 to ascii value to switch to lower case
b = b +((char)x); //typecast and toss into new string
}
if(a.codePointAt(i) == 32 && a.codePointAt(i+1) !=32){
b = b + a.charAt(i);
}
}
return b;
}
}

Java has decent Unicode support. So why do you have to throw all that away and limit yourself to ASCII?

gnasher729
Oct 15, 2007, 08:25 AM
Okay, you could do something like this:-

1) Take the input string and convert it to an array of words. Have a look at using the split() method in String.
2) Loop through your array of words and capitalise the first letter of each word. Use the toUpperCase() and substring() methods of String.
3) Finally, concatenate your array of words together for the final value.


Just one correction: Use toTitleCase(). It is the correct way to capitalise the first character of a word. toUpperCase() is correct if you want to capitalise all characters of a word.

toddburch
Oct 15, 2007, 08:26 AM
Here's your instructor's code, explained.


// String2: what is the output?
import javax.swing.JOptionPane;
public class String2 {
public static void main( String[] args ) {
String s1 = JOptionPane.showInputDialog("Type a word in capital letters: ");
int length = s1.length();

The length of the word the user entered is now held by variable "length".

int counter = 0;
char NextLetter;

Two variables are defined - one of them is initialized.

System.out.println("You entered: " + s1);

Echoing back to the user their word.

while (counter < length) {

The start of a loop. Loop will continue until variable "counter" is not less than variable "length". This will loop 5 times if the word is 5 characters.

NextLetter = s1.charAt(counter);

Initialize variable "NextLetter" with a value. The first time through the loop, since "counter" equals zero, the expression will evaluate to s1.charAt(0), or, in simpler terms, the first character of "s1". If the user entered "APPLE", then "NextLetter" will be "A".

NextLetter += 32;

This has the effect of adding 32 (decimal) to the value held in "NextLetter". A quick glance at an ASCII character chart tells us a decimal 32 (hex X'20') is a blank. It also tells us that an upper case "A" is a decimal 65, and a lower case "a" is a 97. So, if we add 65+32, we get 97. We can deduce that using the ASCII character set, that if you add 32 to an uppercase letter, we get a lowercase letter.

System.out.print(NextLetter);
counter++;
}

Echo the converted character to the user and bump the "counter" so the second time through the loop, counter==1, and we work with the first "P", etc.

System.out.print("\n");
System.exit( 0 );
} // end main
} // end of program


Now, you have just a few pieces of logic to add. First, you have to take into consideration that the user will not just be entering all capital letters. If you add 32 to a lowercase character, you will get garbage output. Looking at an ASCII chart, if you add 97 (lowercase "a") and 32, you get 129, which is a capital A-ring.

Also, you'll have to look for a blank. Blanks don't get converted.

Also, before you convert a letter to uppercase or lowercase, you should probably look to see that is does in fact need to be converted.

As an example, let's say that the user enters:

Coding is fun

If the assignment is to capitalize the first letter of each word, and you subtract 32 from the first letter (because you add 32 to go from uppercase to lowercase, it follows that you would subtract 32 to go from lowercase to uppercase, right?) "C", then that would be a bug in your program, because 67-32 is 35, and you could get a hash mark (#). So, since "C" is already a capital letter, leave it be.

On the next iteration of your loop, since it is not the first letter of the entire string, and it does not follow a blank, it should be converted to lowercase if it is not already lowercase.

Skip ahead to the blank. Blanks don't get converted, but they do tell us to remember to capitalize the next non-blank character.

Next iteration, you get an "i". Since the last character was a blank, if the letter is not already capitalized, it needs to be converted. And, since this character is not a blank, we have to turn off our flag that the last character was a blank before we loop again.

That's pretty much it. Try filling in the syntax to see what you get.

Todd

MBP123
Oct 15, 2007, 08:29 AM
alright thanks i will. What time is best for you?

toddburch
Oct 15, 2007, 08:29 AM
If you think of your assignments as word problems, like you've had in math, then just start writing down all the constraints (or "rules") before you start to code. Just like I did above. Maybe it won't be totally complete on your first pass, but the theory here is to divide and conquer, and not be overwhelmed by the whole assignment.

Todd

toddburch
Oct 15, 2007, 08:31 AM
alright thanks i will. What time is best for you?

45 minutes ago. Read the above and get back.

Todd

lazydog
Oct 15, 2007, 09:00 AM
Just one correction: Use toTitleCase(). It is the correct way to capitalise the first character of a word. toUpperCase() is correct if you want to capitalise all characters of a word.

Good point!

I was hinting at using toUpperCase() only on the first character… it might have been obscure though.

b e n

Blacky
Oct 15, 2007, 05:26 PM
hmm. lots of complicated code with bounds checking and that kind of shizzle?

sure but why not this?


String sentence = "whY dId tHe Duck Eat sTuFF 111!@#$%^&*()";
StringBuilder bob = new StringBuilder();


for (String string : sentence.split(" ")) {
bob.append(string.substring(0, 1).toUpperCase());
bob.append(string.substring(1).toLowerCase());
bob.append(" ");
}

sentence = bob.substring(0, bob.length() - 1);
// or
sentence = bob.toString().trim();

System.out.println(sentence);

toddburch
Oct 15, 2007, 05:35 PM
hmm. lots of complicated code with bounds checking and that kind of shizzle?

sure but why not this?

Why not? Because you don't get to those concepts in the first semester of an Intro to Java programming class. No StringBuffers and no for-each iterators. At least not yet.

Blacky
Oct 15, 2007, 06:07 PM
Why not? Because you don't get to those concepts in the first semester of an Intro to Java programming class. No StringBuffers and no for-each iterators. At least not yet.

Pure semantics, then this would be better?


String sentence = "whY dId tHe Duck Eat a B c sTuFF 111!@#$%^&*()";
String tmp = "";

String[] words = sentence.split(" ");

for (int i = 0; i < words.length; i++) {
tmp += words[i].substring(0, 1).toUpperCase();
tmp += words[i].substring(1).toLowerCase();
tmp += " ";
}

sentence = tmp.trim();

System


I thought people didn't come here to get their homework done but to learn?

if a for is also too much for an introductory course, here is the one that doesn't even need a loop, doesn't need bounds checking, just basic string ops:


public static void main(String[] args) {

String sentence = "whY dId tHe Duck Eat a B c sTuFF!@#$%^&*()";

System.out.println(fixSentence(sentence, true));

}

public static String fixSentence(String string, boolean capitalize){

if (string.length() == 0){ return ""; }

String c = string.substring(0, 1);

if (capitalize){

return c.toUpperCase() + fixSentence(string.substring(1), c.equals(" "));

} else {

return c.toLowerCase() + fixSentence(string.substring(1), c.equals(" "));

}

}

MBP123
Oct 15, 2007, 07:02 PM
i dont know what tmp is although i do appreciate the help and numerous posts. I need to use TextString.charAt(position) and TextString.length()

toddburch
Oct 15, 2007, 07:06 PM
Pure semantics, then this would be better?



I thought people didn't come here to get their homework done but to learn?

if a for is also too much for an introductory course, here is the one that doesn't even need a loop, doesn't need bounds checking, just basic string ops:

Recursive functions. Now that's a step in the right direction. Not.

SC68Cal
Oct 15, 2007, 08:19 PM
It never will meet the condition to go out of bounds and crash the program. You will never have a string that ends with a space which is required to meet the condition, since a.trim removes all extra spaces.

lazydog
Oct 16, 2007, 03:44 AM
I thought people didn't come here to get their homework done but to learn?


I guess that's the idea. It's easy to post code with little explanation that does it in less lines, or in a smarter way than the last person, but it doesn't actually help the OP. On the other hand, Todd has gone out of his way to help the OP.

b e n

MBP123
Oct 16, 2007, 12:25 PM
import javax.swing.JOptionPane;

public class asgn3comments{
public static void main( String[] args )
{
String sentence = JOptionPane.showInputDialog(null,
"Enter a sentence");
boolean first_letter = true;
char this_char;
int upper = 0;
int lower = 0;
int space = 0;
int other = 0;
int counter = 0;
int total = sentence.length();


while (counter < total) {

this_char = sentence.charAt(counter);
if (first_letter == true) { // capitalize all first letter of each word
if (this_char >= 97 && this_char <= 122) {
this_char = s1.charAt(counter);
this_char -= 32;
System.out.print (this_char);
counter++;
// convert to upper case
}
// bump the count of upper case characters.
// reset the flag indicating we will not be looking at a "first letter" next tloop.
}

else { // this is not the first letter. Make sure it is lower case or a blank.
// if this is an upper case letter
// convert it to lower case.
// update count of lower case letters.
}

// print out the letter.
// if this is a blank
// set the flag that tells our loop to capitalize the first letter
// update count of blanks

// print the character withut a line return.

counter++;

}

System.out.println("Total: " + total);
System.out.println("Upper: " + upper);
System.out.println("Lower: " + lower);
System.out.println("Space: " + space);
System.out.println("Other: " + other);
System.out.println("Total: " + total);

} // end main
} // end of program





todd was a HUGE help last night, and made some comments about what to do. I just wanted to make sure that the first part of my while statement was correct before moving on to the rest.

toddburch
Oct 16, 2007, 02:22 PM
Can you explain the differences or similarity between the code in red and the code in blue?

What happened when you tried to compile this?


import javax.swing.JOptionPane;

public class asgn3comments{
public static void main( String[] args )
{
String sentence = JOptionPane.showInputDialog(null,
"Enter a sentence");
boolean first_letter = true;
char this_char;
int upper = 0;
int lower = 0;
int space = 0;
int other = 0;
int counter = 0;
int total = sentence.length();


while (counter < total) {

this_char = sentence.charAt(counter);
if (first_letter == true) { // capitalize all first letter of each word
if (this_char >= 97 && this_char <= 122) {
this_char = s1.charAt(counter);
this_char -= 32;
System.out.print (this_char);
counter++;
// convert to upper case
}
// bump the count of upper case characters.
// reset the flag indicating we will not be looking at a "first letter" next tloop.
}

else { // this is not the first letter. Make sure it is lower case or a blank.
// if this is an upper case letter
// convert it to lower case.
// update count of lower case letters.
}

// print out the letter without a line return.
// if this is a blank
// set the flag that tells our loop to capitalize the first letter
// update count of blanks

counter++;

}

System.out.println("Total: " + total);
System.out.println("Upper: " + upper);
System.out.println("Lower: " + lower);
System.out.println("Space: " + space);
System.out.println("Other: " + other);
System.out.println("Total: " + total);

} // end main
} // end of program

MBP123
Oct 16, 2007, 03:03 PM
i was using my profs example as a guide and thats the variable they used. i meant sentence instead of s1

toddburch
Oct 16, 2007, 03:05 PM
If variable this_char is set once at the top of the WHILE loop, what purpose does it serve to set it again?

MBP123
Oct 16, 2007, 03:31 PM
so i should just remove the second this_char then under the if statement?


a la

import javax.swing.JOptionPane;

public class asgn3comments{
public static void main( String[] args )
{
String sentence = JOptionPane.showInputDialog(null,
"Enter a sentence");
boolean first_letter = true;
char this_char;
int upper = 0;
int lower = 0;
int space = 0;
int other = 0;
int counter = 0;
int total = sentence.length();


while (counter < total) {

this_char = sentence.charAt(counter);
if (first_letter == true) { // capitalize all first letter of each word
if (this_char >= 97 && this_char <= 122) {

this_char -= 32;
System.out.print (this_char);
counter++;
// convert to upper case
}
// bump the count of upper case characters.
// reset the flag indicating we will not be looking at a "first letter" next tloop.
}

else { // this is not the first letter. Make sure it is lower case or a blank.
// if this is an upper case letter
// convert it to lower case.
// update count of lower case letters.
}

// print out the letter.
// if this is a blank
// set the flag that tells our loop to capitalize the first letter
// update count of blanks

// print the character withut a line return.

counter++;

}

System.out.println("Total: " + total);
System.out.println("Upper: " + upper);
System.out.println("Lower: " + lower);
System.out.println("Space: " + space);
System.out.println("Other: " + other);
System.out.println("Total: " + total);


} // end main
} // end of program

toddburch
Oct 16, 2007, 03:39 PM
Good.

Looking at the comments, you have one more thing to do within that IF block.
What is it, and how would you do it?

toddburch
Oct 16, 2007, 03:39 PM
And please - keep the comments near (preferably above) the code that satisfies that comment. ;)

gnasher729
Oct 16, 2007, 03:48 PM
[code[
if (this_char >= 97 && this_char <= 122) {

this_char -= 32;
[/code]

Please, we are in the 21st century.

Try this sentence as input, just for fun (copied from Wikipedia):

An ångström or angstrom (symbol Å) (IPA pronunciation: [ˈæŋstrəm] or [ˈɔŋstrəm]; Swedish: [ˈɔ̀ŋstrœm]) is a non-SI unit of length that is internationally recognized, equal to 0.1 nanometre (nm).

Java gives you all the tools that you need to handle this, with code that is actually a lot easier than yours.

MBP123
Oct 16, 2007, 03:49 PM
Please, we are in the 21st century.

Try this sentence as input, just for fun (copied from Wikipedia):



Java gives you all the tools that you need to handle this, with code that is actually a lot easier than yours.

This is the way my professor wants.

MBP123
Oct 16, 2007, 03:58 PM
so i need to rest the flag indicating we wont be looking for the first letter during the next loop

do i do that by setting first_letter to false?

toddburch
Oct 16, 2007, 04:08 PM
Bingo!

MBP123
Oct 16, 2007, 04:17 PM
while (counter < total) {

this_char = sentence.charAt(counter);
if (first_letter == true) { // capitalize all first letter of each word
if (this_char >= 97 && this_char <= 122) {

this_char -= 32; // convert to uppercase
System.out.print (this_char);
counter++; //bump the count of upper case characters
if (first_letter == false)// reset the flag indicating we will not be looking at a "first letter" next loop.
}


}



so just like that,
and then i have to go to the else statement?

MBP123
Oct 16, 2007, 04:18 PM
actually do i even need the "if" there for setting it to false?

toddburch
Oct 16, 2007, 04:44 PM
Correct, you do not need the IF. You are unconditionally going to set the flag to false.

Now, go on to the ELSE, which is the logic path for test that fail the

if (first_letter == true)

test. We want all these letters to be lower case, which means they have to be converted IF they are uppercase.

MBP123
Oct 16, 2007, 05:06 PM
while (counter < total) {

this_char = sentence.charAt(counter);
if (first_letter == true) { // capitalize all first letter of each word
if (this_char >= 97 && this_char <= 122) {

this_char -= 32; // convert to uppercase
System.out.print (this_char);
counter++; //bump the count of upper case characters
(first_letter == false)// reset the flag indicating we will not be looking at a "first letter" next loop.
}


}

else { // this is not the first letter. Make sure it is lower case or a blank.
if (this_char >= 65 && this_char <= 122) {// if this is an upper case letter
this_char += 32;// convert it to lower case.

// update count of lower case letters.


like this?

toddburch
Oct 16, 2007, 05:12 PM
Looking good!

Get rid of the parens around the setting of the flag to false. They are redundant.

Keep going!!

gnasher729
Oct 16, 2007, 05:21 PM
This is the way my professor wants.

I am very sorry to hear that. I don't know if it would be a good tactical move on your side to show him this post, but I can say that he isn't doing his students any favours, and if the question of converting from lowercase to uppercase came up in a job interview for a software developer, I am quite confident that he would fail.

MBP123
Oct 16, 2007, 05:23 PM
ok so now i am a little stuck as to how to update the count of lower case letters.

toddburch
Oct 16, 2007, 05:24 PM
(first_letter == false)// reset the flag indicating...

When you remove these parens... you won't be done. What else are you forgetting here?

toddburch
Oct 16, 2007, 05:25 PM
OK, reset time. counter is NOT the count of uppercase letters. It is your LOOP control. The comments don't say to update the loop control variable.

Back in your declarations, what variable did you define for the count of uppercase characters? And for lowercase characters? Increment those!

Todd

toddburch
Oct 16, 2007, 05:29 PM
(first_letter == false)// reset the flag indicating...

forgetting here?

AND... this is NOT an assignment. It is a comparison. You want to assign false to the variable.

Not to be rude, but I really think it's time for you to find someone local to you ,to sit down with, and start over with Java from day 1 with you. You're not getting it.

Todd

MBP123
Oct 16, 2007, 05:31 PM
hmm

do i need to do something to have the sentence.charAt?

MBP123
Oct 16, 2007, 05:35 PM
OK, reset time. counter is NOT the count of uppercase letters. It is your LOOP control. The comments don't say to update the loop control variable.

Back in your declarations, what variable did you define for the count of uppercase characters? And for lowercase characters? Increment those!

Todd


while (counter < total) {

this_char = sentence.charAt(counter);
if (first_letter == true) { // capitalize all first letter of each word
if (this_char >= 97 && this_char <= 122) {

this_char -= 32; // convert to uppercase
System.out.print (this_char);
upper++; //bump the count of upper case characters
first_letter == false// reset the flag indicating we will not be looking at a "first letter" next loop.
}


}

else { // this is not the first letter. Make sure it is lower case or a blank.
if (this_char >= 65 && this_char <= 122) {// if this is an upper case letter
this_char += 32;// convert it to lower case.
lower++; // update count of lower case letters.
}

MBP123
Oct 16, 2007, 05:56 PM
is the above code still incorrect?

MBP123
Oct 16, 2007, 06:06 PM
import javax.swing.JOptionPane;

public class asgn3{
public static void main( String[] args )
{
String sentence = JOptionPane.showInputDialog(null,
"Enter a sentence");
boolean first_letter = true;
char this_char;
int upper = 0;
int lower = 0;
int space = 0;
int other = 0;
int counter = 0;
int total = sentence.length();//declared all the variables


while (counter < total) {

this_char = sentence.charAt(counter);
if (first_letter == true) { // capitalize all first letter of each word
if (this_char >= 97 && this_char <= 122) {

this_char -= 32; // convert to uppercase
System.out.print (this_char);
upper++; //bump the count of upper case characters
first_letter == false;// reset the flag so next loop won't look at first letter.
}


}

else { //
if (this_char >= 65 && this_char <= 122) {// if this is an upper case letter
this_char += 32;// convert it to lower case.
lower++; // update count of lower case letters.
}


// print out the letter.
else {
if (this_char == 32) // if this is a blank

// set the flag that tells the loop to capitalize the first letter
space++;// update count of blanks



}


// print the character withut a line return.

counter++;

}

System.out.println("Total: " + total);
System.out.println("Upper: " + upper);
System.out.println("Lower: " + lower);
System.out.println("Space: " + space);
System.out.println("Other: " + other);
System.out.println("Total: " + total);


} // end main
} // end of program


so i think i am getting there? i still dont see what i have to do to that first_letter == false though. i thought you said it was right at first, and now it is not.

MBP123
Oct 16, 2007, 07:15 PM
anyone?

MBP123
Oct 16, 2007, 09:26 PM
first_letter == false;// reset indicating we will not be looking at a "first letter" next loop.

this one line is really screwing me over

i cant seem to figure it out

therevolution
Oct 17, 2007, 01:46 AM
There is a difference between

first_letter == false;

which is a comparison and evaluates to either true or false (is the value assigned to first_letter equal to false?), and

first_letter = false;

which assigns the value false to first_letter.

janey
Oct 17, 2007, 05:27 AM
Not to be rude, but I really think it's time for you to find someone local to you ,to sit down with, and start over with Java from day 1 with you. You're not getting it.
todd++

Office hours with the prof, tutoring, other students, IRC, forums...preferably something in person..is not a bad idea. Sometimes you just have to talk things over with someone who can help you go in the right direction. You need have a good foundation to start with - insufficient knowledge of loops (among other things)? Fix that right now before you get even more lost in class. Asking for help on every single assignment is going to do you no good at all, especially when you have everyone gently prodding you towards the right answer.

gettysburg
Sep 1, 2010, 08:54 PM
Hey there. This is the simplest way to go about the task you're trying to accomplish.

import javax.swing.JOptionPane;

public class Capitalize
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Enter a word.");
String firstLetter = input.substring(0,1);
String remainder = input.substring(1);
String goodInput = firstLetter.toUpperCase() + remainder.toLowerCase();
JOptionPane.showMessageDialog(null, goodInput);
}
}

chown33
Sep 1, 2010, 09:15 PM
Your code doesn't solve the posted problem, which is to capitalize every word in a sentence, not a single word. See the original post:
http://forums.macrumors.com/showthread.php?t=368861

And congrats for reviving a 3-year-old thread. Inauspicious first post.