I have the following code, to show by cycle and letter by letter, the content in each index of the array caracter
:
Scanner ins = new Scanner(System.in);
String caracter;
System.out.println("Ingrese cualquier palabra o frase");
caracter = ins.next();
for (int indice=0;indice<=caracter.length();indice++){
System.out.println(caracter.charAt(indice));
}
It works correctly with words or strings of consecutive characters, but when I enter a compound phrase with spaces and words, after going through the cycle, the program jumps with an error in the index that corresponds to the white space:
According to the error, it gives me to understand that from the word Le , everything that is in front of it, it is not possible to capture it with the method charAt(x)
. And if it is impossible, is there another way to do it?
There are two things you have to change:
The first: Use the method
nextLine()
, instead ofnext()
. Since the first reads whitespace and the second doesn't. That's why I only give him the first word.The second: The exception is thrown because you don't define the loop well. It is
indice<caracter.length()
, and it is notindice<=caracter.length()
.All together: