Link to home
Start Free TrialLog in
Avatar of b_acs
b_acsFlag for United States of America

asked on

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

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

Avatar of b_acs
b_acs
Flag of United States of America image

ASKER

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

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

Avatar of b_acs

ASKER

That makes sense to create a method instead of copying the same code....Thanks!
Avatar of Mick Barry
the whole thing should be a separate method

public String capitalize(String line)

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.
Avatar of b_acs

ASKER

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

Avatar of b_acs

ASKER


//******************************************************************
// 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

Avatar of b_acs

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of oleber
oleber
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial