简体   繁体   English

在单词之间添加空格并在java中创建除第一个小写之外的每个单词

[英]Adding Spaces between words and making every word except the first lowercase in java

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. 我也是Java的新手,我还在学习这门语言。

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");
}

} }

You are appending to the same string that you are iterating through. 您将附加到您正在迭代的相同字符串。 Instead, just make your sentence an empty StringBuilder . 相反,只需将您的sentence StringBuilderStringBuilder Then you can append to that while iterating through input . 然后你可以在迭代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.) (请注意,我已经将变量名称从index更改为letter ,这更容易让人困惑。)

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. 所以index就是角色本身。 Java implicitly converts this character to an integer - but it's not the integer that you want it to be. Java隐式地将此字符转换为整数 - 但它不是您希望它的整数。 You probably should have written 你应该写的

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

instead. 代替。

Also, your sentence.append(' '); 还有,你的sentence.append(' '); will append the space to the end of the StringBuilder , rather than inserting it where you want it to. 将空格附加到StringBuilder的末尾,而不是将其插入到您想要的位置。

And your final sentence.append(index); 而你的最后sentence.append(index); will duplicate the character. 将复制角色。 I really don't think you want to do this. 我真的不认为你想这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 java 中的每个单词之间添加空格 - adding space in between every word in java 字符之间的正则表达式空格(Java 开头除外) - Regex spaces between chars except the beginning Java 正则表达式:Java:2个空格之间的匹配词 - regex: Java: match word between 2 spaces 为除尖括号外的非字符之外的每个单词添加标签 - Adding tags to every word except non characters outside angle brackets Java Regex:以&#39;s&#39;结尾的单词(特定单词除外) - Java Regex: word ending in 's' except specific words 除了java中的First Element之外,在Elements之间添加新的行分隔符而不是Comma - Adding new line delimitter instead of Comma between Elements except the First Element in java 输入字符串,将每个单词解析为所有小写字母并将每个单词打印在一行上,非字母字符被视为单词之间的分隔符 - Take string input, parse each word to all lowercase and print each word on a line, non-alphabetic characters are treated as a break between words 根据单词之间的空格查找文本的宽度(JAVA) - Finding the width of a text depending on spaces between words (JAVA) 一个 output 如何在 codeRunner 中返回 java 中的单词之间没有空格? - How does one output into codeRunner to return with no spaces between the words in java? 在java中的String中的每个单词中首字母大写(但忽略特定单词) - Capitalizing first char in every word in a String in java (but ignoring specific word)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM