I want each line to split off after 20 characters have gone by, but I want it to split off at the nearest space so the sentence has only whole words.
The answerer said to do this:
str="some long string"
startPos=0, endPos=0
while (startPos < str.length) {
determine endPos
print substring from startPos to endPos
move startPos to endPos+1 // this is the part I am confused about.
}
The code I wrote was this:
System.out.println("Please input a word: ");
Scanner stringScanner = new Scanner(System.in);
String input = stringScanner.nextLine();
int startPos = 0;
int endPos = 0;
while (startPos < input.length()) {
endPos = 20;
System.out.println(input.substring(startPos, endPos));
startPos = endPos + 1; //This is the part I am confused about
}
I am not sure what the answerer means by move startPos to endPos + 1. Any answers would helo, thanks.
Edit:
sorry I forgot to post what my code does:
The program right now give me an error that says this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 21, end 20, length 32
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:4602)
at java.base/java.lang.String.substring(String.java:2705)
at StarBorder.StarBorder.main(StarBorder.java:18)
This is what I want it to do:
Hello there, I am
doing some coding,
I need some help