Capitalize Java string?

Discussion in 'Mac Programming' started by MBP123, Oct 14, 2007.

  1. MBP123 macrumors regular

    Joined:
    May 26, 2006
    #1
    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
     
  2. sord macrumors 6502

    Joined:
    Jun 16, 2004
    #2
  3. MBP123 thread starter macrumors regular

    Joined:
    May 26, 2006
    #3
    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.
     
  4. MBP123 thread starter macrumors regular

    Joined:
    May 26, 2006
    #4
    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.
     
  5. sord macrumors 6502

    Joined:
    Jun 16, 2004
    #5
    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.
     
  6. MBP123 thread starter macrumors regular

    Joined:
    May 26, 2006
    #6
    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. ");


    ?
     
  7. MBP123 thread starter macrumors regular

    Joined:
    May 26, 2006
    #7
    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?
     
  8. sord macrumors 6502

    Joined:
    Jun 16, 2004
    #8
    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?
     
  9. sord macrumors 6502

    Joined:
    Jun 16, 2004
    #9
    If you used that, you would use capitalize with your s1, then output its result.
     
  10. MBP123 thread starter macrumors regular

    Joined:
    May 26, 2006
    #10
    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
    
    
    
     
  11. SC68Cal macrumors 68000

    Joined:
    Feb 23, 2006
    #11
    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;
    	}
    }
     
  12. Persifleur macrumors member

    Joined:
    Jun 1, 2005
    Location:
    London, UK
    #12
    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().
     
  13. lazydog macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #13
    If I'm not mistaken you have a couple of bugs in your code.

    b e n
     
  14. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #14
    This is why I would never use the non-human representation of a character in source code.

    Can you say "out of range"?

    Todd
     
  15. MBP123 thread starter macrumors regular

    Joined:
    May 26, 2006
    #15
    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
     
  16. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #16
    AIM me and I'll walk you through your instructor's example.

    Todd
     
  17. lazydog macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #17
    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
     
  18. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #18
    Java has decent Unicode support. So why do you have to throw all that away and limit yourself to ASCII?
     
  19. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #19
    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.
     
  20. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #20
    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
     
  21. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #21
    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
     
  22. MBP123 thread starter macrumors regular

    Joined:
    May 26, 2006
    #22
    alright thanks i will. What time is best for you?
     
  23. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #23
    45 minutes ago. Read the above and get back.

    Todd
     
  24. lazydog macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #24
    Good point!

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

    b e n
     
  25. Blacky macrumors member

    Joined:
    Jun 27, 2007
    #25
    hmm. lots of complicated code with bounds checking and that kind of shizzle?

    sure but why not this?

     

Share This Page