6
I’m having a question about how to remove spaces from a Java string by doing this through the for
.
I’m making a letter diamond, and I use a variable to create the space between the letters.
A
B B
C C
D D
E E
F F
G G
I was able to assemble the top of the diamond, but we need to do the bottom, and I need to use the variable that contains all the spaces. My idea is to take the space between the 2 F and decrease 2 spaces at each loop until it reaches the letter A.
If you can help me, thank you, because I’m cracking my skull to solve this simple problem.
Below is the code I made, it got big, because I’m new in java and programming in general, and I don’t have the techniques yet:
public class Diamante {
public void MontarDiamante()
{
//PARTE SUPERIOR
String espaço = {" ", " ", " "...etc} // Coloquei 26 posições de espaços para cada uma das letras do alfabeto para criar os espaços que ficam do lado esquerdo de fora do diamante.
int x = 0;
String espacoLetras = " ";
String alfabeto[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String letra = JOptionPane.showInputDialog("Diamante de Letras\nInsira uma Letra: ");
for(int c = 0; c < alfabeto.length; c++)
{
if(c == 0)
{
System.out.println(espacos[0]+alfabeto[0]);
}
System.out.println(espacos[c+1]+alfabeto[c+1]+espacoLetras+alfabeto[c+1]);
espacoLetras = espacoLetras + " ";
if(letra.equals(alfabeto[c+1]))
{
x = c;
break;
}
}
//PARTE INFERIOR DO DIAMANTE
for(int i = x; i >= 0 ; i--)
{
espacoLetras = espacoLetras.trim();
System.out.println(espacos[i]+alfabeto[i]+espacoLetras+alfabeto[i]);
/*if(i == 0)
{
System.out.println(espacos[i]+alfabeto[i]);
}*/
}
}
public static void main(String args[])
{
Diamante d = new Diamante();
d.MontarDiamante();
}
}
It would be easier to understand what you are doing if you showed the code that makes the top half. Doing this by replacing spaces is possible, but I would need to know which variables you are talking about.
– Victor Stafusa