Could try iterating with a class instance string
. And iterate the characters of this String with the method charAt
.
Follow an example:
public static void main(String args[]) {
String vetor = "corrida";
char c;
for(int i = 0; i<=vetor.length()-1; i++) {
c = vetor.charAt(i);
System.out.println(c);
}
}
To try to solve your specific problem you could mount the message you want to display on optionPane using an auxiliary variable.
In my example I changed the type of String
for StringBuilder
for reasons of efficiency. When using the Stringbuilder class we must interact with the methods exposed by the Stringbuilder class, in this case to concatenate just use the method append()
.
Example:
public static void main (String[] args) {
final String separador = System.getProperty("line.separator");
String vetor = "corrida";
char c;
StringBuilder tmpmsg = new StringBuilder();
for(int i = 0; i<=vetor.length()-1; i++) {
c = vetor.charAt(i);
//tmpmsg.append(c).append(separador); #para utilizar quebra de linha
tmpmsg.append(c).append(' '); // #para utilizar espaços
}
System.out.println(tmpmsg);
// agora só precisa criar 1 instância do jOptionPane (não é necessário fazer um for)
JOptionPane.showMessageDialog(null, "Mensagem divida por caractere: " + tmpmsg);
}
In this example I am using the method System.getProperties
which is a helper function to facilitate access to a property of the operating system where the JVM is running. In this case I am wanting to get the line separator property (line.separator
). For a complete list of which properties can be accessed just go to documentação do método getProperties
.
There are some things to improve in this code such as modularizing actions.
Do not forget to accept any of the answers if they have answered you
– Sorack