I am getting an error with this code
import java.util.Scanner; public class five { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String sentence = "Please enter a line of text. No punctuation please"; System.out.print(sentence); String s1, firstWord, firstLetter, endSentence, newSentence; s1 = keyboard.nextLine(); int wordEndLoc = s1.indexOf(' '); //retrieve the first word to be replaced firstWord = s1.substring(0,wordEndLoc); //get the second part of the sentence without the first word and trim trailing spaces endSentence = s1.substring(wordEndLoc,s1.length()).trim(); //combine the second part with the first word at the end newSentence = endSentence + " " + firstWord; //retrieve he first letter of the newly organized sentence, and capitalize it as well firstLetter = newSentence.substring(0,1).toUpperCase(); //again, get the second part of the sentence (without the first letter) endSentence = newSentence.substring(1,s1.length()); //combine the first letter with the second part newSentence = firstLetter + endSentence; String mess2 = "I have replaced that line to read: "; System.out.print(mess2); System.out.print(newSentence); } }
My output says
Please enter a line of text. No punctuation please
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at five.main(five.java:18)