Я пойду дальше и дам вам знать, что да, это домашнее задание. Я ударил кирпичную стену, выполняя ее, но отчаянно нуждаясь в помощи. Я также довольно новичок в Java и до сих пор изучаю язык.Добавление пробелов между словами и создание каждого слова, кроме первого строчного регистра в java
Хорошо, я пытаюсь написать программу, которая просит пользователя ввести предложение без пробелов, но запишите их в первую букву каждого слова. Затем программа должна добавить пробелы между словами и загладить только первое слово, остальные должны начинаться с строчной буквы. Я могу получить пространство, вставленное между словами, но я не могу получить первую букву каждого слова с нижней частью. Я попробовал несколько различных способов, и последняя из них дает мне сообщение об ошибке:
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)
Я отправляю мой код и любые и все помочь вы можете дать мне будет очень высоко ценится. Спасибо.
/*
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");
}
}
+1 за ответ, и он может получить его желаемый результат при хранении вход с использованием «temp = предложение», а затем окончательный результат будет «System.out.println (« \ n \ n ». Теперь ваше предложение:« + предложение.ремени (0, temp.length(), «»)); ' –
@VinayakPingale Он мог получить желаемый результат только с' предложением'. Мне не нужно было менять какой-либо код OP за пределы того, что у меня было выше. – chrisaycock
Это прекрасно работает, спасибо! Я потратил часы, пытаясь понять это, и вы исправили его в трех строках кода, вы, сэр, сейчас мой герой. –