Pregunta

I'll go ahead and let you know that yes, this is homework. I have hit a brick wall in completing it however and desperately need help. I'm also pretty new to Java and am still learning the language.

Okay, I am trying to write a program that asks the user to enter a sentence with no spaces but have them capitalize the first letter of each word. The program should then add spaces between the words and have only the first word capitalized, the rest should start with a lowercase. I can get the space inserted between the words, but I cannot get the first letter of each word lower-cased. I have tried several different ways, and the latest one is giving me this error message:

 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
 ex out of range: 72
    at java.lang.AbstractStringBuilder.setCharAt(Unknown Source)
    at java.lang.StringBuilder.setCharAt(Unknown Source)
    at renfroKristinCh9PC14.main(renfroKristinCh9PC14.java:45)

I'm posting up my code and any and all help you can give me will be very much appreciated. Thanks.

/*
This program will ask the user to enter a sentence without whitespaces, but 
with the first letter of each word capitilized. It will then separate the words
and have only the first word of the sentence capitalized.
*/

import java.util.*;

public class renfroKristinCh9PC14
{
public static void main(String[] args)
{
    //a string variable to hold the user's input and a variable to hold the modified sentence
    String input = "";
    //variable to hold a character
    char index;

    //create an instance of the scanner class for input
    Scanner keyboard = new Scanner(System.in);

    //welcome the user and explain the program
    userWelcome();

    //get the sentence from the user
    System.out.println("\n  Please enter a sentence without spaces but with the\n");
    System.out.println("  first letter of each word capitalized.\n");
    System.out.print("  Example: BatmanIsTheBestSuperheroEver!  ");

    input = keyboard.nextLine();

    //create an instance of the StringBuilder class
    StringBuilder sentence = new StringBuilder(input);

    //add spaces between the words
    for(int i=0; i < sentence.length(); i++)
    {
        index = sentence.charAt(i);
        if(i != 0 && Character.isUpperCase(index))
        {

            sentence.setCharAt(index, Character.toLowerCase(index));
            sentence.append(' ');


        }

        sentence.append(index);

    }   


    //show the new sentence to the user
    System.out.println("\n\n  Your sentence is now: "+sentence);
}
/***********************************************************************************    *************************
************************************************************************************    *************************

This function welcomes the user and exlains the program
*/

public static void userWelcome()
{

    System.out.println("\n\n       ****************   ****************************************************\n");
    System.out.println("  *            Welcome to the Word Seperator Program                   *");
    System.out.println("  *  This application will ask you to enter a sentence without       *");
    System.out.println("  *  spaces but with each word capitalized, and will then alter the  *");
    System.out.println("  *  sentence so that there arespaces between each word and          *");
    System.out.println("  *  only the first word of the sentence is capitalized              *");
    System.out.println("\n  ********************************************************************\n");
}

}

¿Fue útil?

Solución

You are appending to the same string that you are iterating through. Instead, just make your sentence an empty StringBuilder. Then you can append to that while iterating through input. For example:

StringBuilder sentence = new StringBuilder();

//add spaces between the words
for(int i=0; i < input.length(); i++)
{
  char letter = input.charAt(i);
  if(i != 0 && Character.isUpperCase(letter))
  {
    sentence.append(' ');
    sentence.append(Character.toLowerCase(letter));
  }
  else
  {
    sentence.append(letter);
  }
}   

(Note that I've changed the variable name from index to letter, which is a lot less confusing.)

Otros consejos

You have a few different problems here. The main one is that when you call

sentence.setCharAt(index, Character.toLowerCase(index));

you're passing in the actual character in as the first argument, instead of the position. You see, you've just done

index = sentence.charAt(i);

so index is the character itself. Java implicitly converts this character to an integer - but it's not the integer that you want it to be. You probably should have written

sentence.setCharAt(i, Character.toLowerCase(index));

instead.

Also, your sentence.append(' '); will append the space to the end of the StringBuilder, rather than inserting it where you want it to.

And your final sentence.append(index); will duplicate the character. I really don't think you want to do this.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top