Hi. I have made a program that wraps the text into a spesific length, but there is a small problem that I cant solve. Why does the program exceed the length when the next String is exactly the same length as the remaining line. Here is the code:
import java.util.*;
publicclass StringTraining {
publicstaticvoid main ( String[] args ) {
StringTraining Test = new StringTraining ();
String text = "This is the text that should be manipulated correctly"+
" but there is a problem with it! I have tried to figure it out for"+
" several hours. When the string is the same size as the remaining"+
" space there is an error Please help, this is driving me crazy";
text = Test.Manipulate ( text, 30 );
System.out.println ( text );
} // main
public String Manipulate ( String text, int length ) {
StringBuffer sb = new StringBuffer ( );
StringTokenizer st = new StringTokenizer ( text );
int temp = length;
while ( st.hasMoreTokens() ) {
String next_string = st.nextToken();
int srting_length = next_string.length();
if ( srting_length < temp ) {
sb.append ( next_string+" ");
temp = ( (temp - srting_length) -1);
} //if
elseif ( srting_length > temp ) {
char [] target = next_string.toCharArray();
for ( int n = 0; n < srting_length; n++ ) {
sb.append(target[n]);
--temp;
if (temp <= 0 ) {
n++;
sb.append("\n"+target[n]);
temp = ((length)-1);
}//if
}//for
sb.append(" ");
temp--;
}//else if
} //while
return sb.toString();
} //Manipulate
} //StringTraining