Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How do I capitalize the first letter of a sentence in Java?

Posted on 2009-04-18
9
Medium Priority
?
4,332 Views
Last Modified: 2013-11-23
I am working on a homework assignment and have gotten close to the final working version.  
I am just looking for some help to see where I am going wrong.  I get output errors when I run this.  The first letters in the first word of my sentences are capitalized but I get some goofy output on some words and puncuation.  Can anyone see why?

Thanks
package sentence_caps;
 
import java.util.Scanner;
 
public class Sentence_Caps {
	
    public static void main(String[] args){
    	//Get user input            
    	Scanner keyboard = new Scanner(System.in);
    	System.out.println("Please input your sentence(s): ");
    	String str = keyboard.nextLine();
                     //a sample string for debugging purposes
    	//String str = 
                     ("hi! it is a splendid day. my name is Joe? do you know the muffin man? yes I do!");
    	String[] tokens = str.split(" ");
    	String capitalize = "";
    	for (int i = 0; i < tokens.length; i++){
    	// edit the loop so we can access values related to the current one
    		if (!tokens[i].equals("")){
    		// if we didn't have this...things would go wrong.
    			if (i == 0){
    				capitalize += tokens[i].substring(0, 1).toUpperCase() 
    				+ tokens[i].substring(1, tokens[i].length() - 1);
    			}else if (tokens[i - 1].endsWith(".")){
    				capitalize += " " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1,2)+
    				tokens[i].substring(1, tokens[i].length() - 1);
    			}else if (tokens[i - 1].endsWith("!")){
    				capitalize += "! " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1,2)+
    				tokens[i].substring(1, tokens[i].length() - 1);
    			}else if (tokens[i - 1].endsWith("?")){
    				capitalize += " " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1,2)+
    				tokens[i].substring(1, tokens[i].length() - 1);
    			}else if (tokens[i - 1].equals("")){
    				capitalize += ". " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1,2)+
    				tokens[i].substring(1, tokens[i].length() - 1);
    				 //If none of the above are true then
    			}else{
    				capitalize += " " + tokens[i];
    				}
    		}
    	}// END FOR LOOP
 
	   	System.out.println(capitalize);
    }
}

Open in new window

0
Comment
Question by:b_acs
  • 5
  • 3
9 Comments
 

Author Comment

by:b_acs
ID: 24177821
Well I don't know why but I could not figure this out.  Then as soon as I post the question I see where my problem was. I have figured this out and am posting the code....

I will appreciate any comments you may have on improving this though.

Thanks again

B_Acs
package sentence_caps;
 
import java.util.Scanner;
 
public class Sentence_Caps {
	
    public static void main(String[] args){
    	// Get user input            
    	Scanner keyboard = new Scanner(System.in);
    	System.out.println("Please input your sentence(s): ");
    	String str = keyboard.nextLine();
    	//String str = 
    	//("hi! it is a splendid day. my name is Joe? do you know the muffin man? yes I do!");
    	// Split the string using a space as a delimiter
    	String[] tokens = str.split(" ");
    	// create a variable to put the final string in
    	String capitalize = " ";
    	for (int i = 0; i < tokens.length; i++){
    	// edit the loop so we can access values related to the current one
    		if (!tokens[i].equals("")){
    			// Capitalize the first letter of the first word(token) 
    			// Then add on the remaining words only capitalizing the tokens
    			// that have a punctuation mark before them (e.g. "?, !, .)
    			if (i == 0){
    				capitalize += tokens[i].substring(0, 1).toUpperCase() 
    				+ tokens[i].substring(1);
    			}else if (tokens[i - 1].endsWith(".")){
    				capitalize += " " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1);
    			}else if (tokens[i - 1].endsWith("!")){
    				capitalize += " " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1);
    			}else if (tokens[i - 1].endsWith("?")){
    				capitalize += " " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1);
    			}else if (tokens[i - 1].equals("")){
    				capitalize += " " + tokens[i].substring(0, 1).toUpperCase() +
    				tokens[i].substring(1);
    				 //If none of the above are true then
    			}else{
    				capitalize += " " + tokens[i];
    				}
    		}
    	}// END FOR LOOP
    	// Print the manipulated string
	   	System.out.println(capitalize);
    }
}

Open in new window

0
 
LVL 10

Expert Comment

by:oleber
ID: 24178475
your code is similar to:
package sentence_caps;
 
import java.util.Scanner;
 
public class Sentence_Caps {
	static String toUpperCaseFirst(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}
	public static void main(String[] args){
		// Get user input            
		Scanner keyboard = new Scanner(System.in);
		System.out.println("Please input your sentence(s): ");
		String str = keyboard.nextLine();
		//String str = 
		//("hi! it is a splendid day. my name is Joe? do you know the muffin man? yes I do!");
		// Split the string using a space as a delimiter
		String[] tokens = str.split(" ");
		// create a variable to put the final string in
		String capitalize = " ";
		for (int i = 0; i < tokens.length; i++){
			// edit the loop so we can access values related to the current one
			if (!tokens[i].equals("")){
				// Capitalize the first letter of the first word(token) 
				// Then add on the remaining words only capitalizing the tokens
				// that have a punctuation mark before them (e.g. "?, !, .)
				if (i == 0){
					capitalize += toUpperCaseFirst(tokens[i]);
				} else if (tokens[i - 1].matches(".*(\\.|\\!|\\?)|")){
					capitalize += " " + toUpperCaseFirst(tokens[i]);
				} else{
					capitalize += " " + tokens[i];
 
				}
			}
		}// END FOR LOOP
		// Print the manipulated string
		System.out.println(capitalize);
	}
}

Open in new window

0
 

Author Comment

by:b_acs
ID: 24178526
That makes sense to create a method instead of copying the same code....Thanks!
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Expert Comment

by:objects
ID: 24181261
the whole thing should be a separate method

public String capitalize(String line)

0
 
LVL 10

Expert Comment

by:oleber
ID: 24182230
that depends in the work in hands.

the separate toUpperCaseFirst is logic since it removes copy&paste code.

If the code is supposed to simply capitalize the first character, you don't need a new function just for that for now.
0
 

Author Comment

by:b_acs
ID: 24182583
Well here is what I have for my final program....btw I did seperate the method and main into two seperate classes.  That is the way I was taught to do it.  
(When I am working on code I leave it all in one.)

Thank you for your comments!

B_Acs
//******************************************************************
// Chapter 8                                          			   *
// Programming Challenge 3, Sentence Capitalizer      			   *
//******************************************************************
 
//******************************************************************
// Write a method that accepts a String object as an argument 	   *
// and returns a copy of the string with the first character of    *
// each sentence capitalized.  For instance, if the argument is    *
// "hello. my name is Joe. what is your name?" the method should   *
// return the string, "Hello. My name is Joe. What is your name?"  *
// Demonstrate the method in a program that asks the user to input *
// a string and then passes it to the method. The modified string  *
// should be displayed on the screen.							   *
//******************************************************************
 
package sentence_caps;
 
public class Sentence_Caps{
 
//******************************************************************
// The capitalization method accepts a String as an argument, and  *
// loops through the string calling the First method to capitalize *
// the first letter of the first word in each sentence.			   *
//******************************************************************
	
	public static void capitalization(String inputSentence)
	{
		//Variable declarations.
		
		String capitalized = ""; // Put the correct cased parts together.
		
		//Process - Separate word into parts, change case, put together.
	
		String[] input = inputSentence.split(" ");
		
		// Loop through and Capitalize the first word of each sentence.
		for(int i = 0; i < input.length; i++)
		{	
			// initialize to blank string
			capitalized = "";	
			// Capitalize the first letter of the first word; Then add on
			// the remaining words only capitalizing the first letter of the
			// words that have a punctuation mark before them (e.g. "?, !, .)
			if (i == 0){
				capitalized += First(input[i]);
			}else if (input[i - 1].endsWith(".")){
				capitalized += First(input[i]);
			}else if (input[i - 1].endsWith("!")){
				capitalized += First(input[i]);
			}else if (input[i - 1].endsWith("?")){
				capitalized += First(input[i]);
			}else if (input[i - 1].equals("")){
				capitalized += " " + First(input[i]);
				//If none of the above are true then
			}else{
				capitalized += input[i];
			}
			// Print each word with a space afterward 
			System.out.print(capitalized + " ");
		}
		
	}
 
//******************************************************************
// The First method accepts a String as an argument, and  		   *
// returns it with the first letter of the word capitalized.       *
//******************************************************************
 
	private static String First(String input) {
		String firstLetter = input.substring(0, 1).toUpperCase();
		String remainder = input.substring(1);
		return firstLetter + remainder;
	}
}

Open in new window

0
 

Author Comment

by:b_acs
ID: 24182585

//******************************************************************
// Chapter 8                                          			   *
// Programming Challenge 3, Sentence Capitalizer Demo  			   *
//******************************************************************
 
//******************************************************************
// Demonstrates the Sentence_Caps class							   *
//******************************************************************
	package sentence_caps;
 
	import java.util.Scanner;
	
	public class SentenceCapsDemo {
				
	    public static void main(String[] args){
	    	
	    	// Create a Scanner object for keyboard input.
	    	Scanner keyboard = new Scanner(System.in);
	    	
	    	//Get user input and place into a string variable
	    	System.out.println("Please input your sentence(s): ");
	    	String input = keyboard.nextLine();
	    	
	    	//Process - Separate word into parts, change case, put together.
	    	Sentence_Caps.capitalization(input);	
	    }
	}     
	    

Open in new window

0
 

Author Comment

by:b_acs
ID: 24182593
I will leave this open for a couple more days because I would like to see if anyone else has any comments for me.  I am brand new to Java and will appreciate any comments that will help me learn.  I really like solving problems and think I may go into programming when I finish school.

Thank you all!

B_Acs
0
 
LVL 10

Accepted Solution

by:
oleber earned 1000 total points
ID: 24185949
To use standards the code, change:
package sentence_caps; => package sentenceCaps;
class Sentence_Caps => class SentenceCaps
First(String input) => upperlCaseFirst(String input)

#####################################################

Why do you have?
}else if (input[i - 1].equals("")){
    capitalized += " " + First(input[i]);
}

#####################################################

Simplify the code

public static void capitalization(String inputSentence)
{
    //Variable declarations.

    String capitalized = ""; // Put the correct cased parts together.

    //Process - Separate word into parts, change case, put together.

    String[] input = inputSentence.split(" ");

    // Loop through and Capitalize the first word of each sentence.
    for(int i = 0; i < input.length; i++)
    {
        // initialize to blank string
        capitalized = "";
        // Capitalize the first letter of the first word; Then add on
        // the remaining words only capitalizing the first letter of the
        // words that have a punctuation mark before them (e.g. "?, !, .)

        if (i == 0){
            capitalized += first(input[i]);
        }else if (input[i - 1].equals("")){
            capitalized += " " + first(input[i]);
        }else {
            char lastChar = input[i - 1].charAt(input[i - 1].length() - 1);
            if (".!?".indexOf(lastChar) >= 0){
                capitalized += first(input[i]);
            }else{
                capitalized += input[i];
            }
        }
        // Print each word with a space afterward
        System.out.print(capitalized + " ");
    }
}

0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month20 days, 22 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question