1
I’m trying to solve a little java dojo:
Write a program in which given a sentence and the amount of columns that can be displayed on the screen, break lines without breaking the words. For example, if we pass the phrase "A small, nosy Jabuti saw ten happy storks." and ask for it to be displayed in 20 columns, we will have as a response:
Um pequeno jabuti
xereta viu dez
cegonhas felizes.
But in my code he’s breaking the word after the 20 character.
public static void main(String[] args) {
String texto = "Um pequeno jabuti xereta viu dez cegonhas felizes.";
String novoTexto = "";
int contadorQntLetras = 0;
int limiteLinha = 20;
for( int i = 0; i < texto.length(); i++ ) {
novoTexto += texto.charAt(i);
contadorQntLetras++;
if( contadorQntLetras >= limiteLinha) {
contadorQntLetras = 0;
novoTexto += "\n";
}
}
System.out.println(novoTexto);
}
Upshot:
Um pequeno jabuti xe
reta viu dez cegonha
s felizes.