Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MBP123

macrumors regular
Original poster
May 26, 2006
192
0
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
 
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.
 
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.
 
This splits the input (that you may have received from any way you want) into arrays with spaces as the delimeter
Code:
String[] words = line.split("\\s");
Then as they are iterating, they are doing this:
Code:
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.
 
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. ");


?
 
This splits the input (that you may have received from any way you want) into arrays with spaces as the delimeter
Code:
String[] words = line.split("\\s");
Then as they are iterating, they are doing this:
Code:
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?
 
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 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.
 
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.


Code:
// 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
 
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.

Code:
//
//  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;
	}
}
 
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().
 
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.

Code:
//
//  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
 
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
 
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
 
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.

Code:
//
//  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?
 
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.
 
Here's your instructor's code, explained.

Code:
// 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".
Code:
	 int counter = 0;
	 char NextLetter;
Two variables are defined - one of them is initialized.
Code:
     System.out.println("You entered: " + s1);
Echoing back to the user their word.
Code:
	 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.
Code:
	 	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".
Code:
	 	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.
Code:
		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.
Code:
		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
 
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
 
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
 
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);
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.