Im doing an assignment and it asks to do a few things with a text that the user types. Im stuck at the very end were it asks to:
- Create a matrix[10][10] to stored Strings.
- Distribute every letter stored in the vector in different positions of the matrix. Starting on the first line, drawn the positions of every letter using Math.random(). The letters can't be more than 2 positions apart.
- Store each element of the vector in the drawn position of the matrix and print the result.
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Type a phrase with no more than 50 characters.");
String frase = entrada.nextLine();
while (frase.length() > 50) {
System.out.println("The phrase has more than 50 characters. Try again.");
frase = entrada.nextLine();
}
frase = frase.replace(" ", "");
frase = frase.toUpperCase();
int carac = frase.length();
System.out.println("");
System.out.println("The size of the phrase is: " + carac);
String[] vet = new String[carac];
for (int i = 0; i < carac; i++) {
vet[i] = String.valueOf(frase.charAt(i));
System.out.print(vet[i]);
}
System.out.println("");
String[][] gabarito = new String[10][10];
int posicaoV = 0;
for (int i = 0; i < 10; i++) {
int posicaoJ = 0;
for (int j = posicaoJ; j < 10; j++) {
int sorteio = (int) (Math.random() * 3);
posicaoJ = posicaoJ + sorteio;
if (posicaoJ > 9) {
break;
}
gabarito[i][posicaoJ] = vet[posicaoV];
posicaoV++;
}
if (posicaoJ > 9) {
break;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (gabarito[i][j] == null) {
System.out.print(" ");
} else {
System.out.print(gabarito[i][j]);
}
}
System.out.println("");
}
}
The problem that I'm having is that the code jumps a few letters instead of going through them all. Its also very inconsistent, sometimes it stops after 5 letters and other types it prints everything, and sometimes I even get a outofbound error. I have been trying for hours and ran out of ideas at this point.
Aucun commentaire:
Enregistrer un commentaire