I'm doing a program to encrypt according to the Cipher of Caesar in Java. I came across the following problem in the code:
package projects;
import java.util.Scanner;
public class Projects {
public static void main(String[] args) {
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
Scanner scanner = new Scanner(System.in);
String palavraLida = "";
System.out.println("Digite a palavra que você quer criptografar:");
palavraLida = scanner.nextLine();
System.out.println("Digite a chave para o processo (0 - 25)");
int chaveString = scanner.nextInt();
char[] palavraGerada = new char[palavraLida.length()];
int index = 0;
if(chaveString <= 25 && chaveString >=0){
for (int i = 0; i < palavraLida.length(); i++) {
if (palavraLida.toCharArray()[i] == ' ') {
palavraGerada[i] = '#'; // Se for um espaco, cria uma hashtag na string de saída
}else{
//Se não for, checa de acordo com o alfabeto
for (int j = 0; j < palavraLida.length(); j++) {
if (palavraGerada[i] == alphabet[j]) {
index = j + chaveString;
if(index >= 26){
index = index - 26;
}
palavraGerada[i] = alphabet[index];//Grava na array de saída de acordo com a variável correspondente
}
}
}
}
}else{
System.out.println("Chave inválida.\n");
}
System.out.println(palavraGerada);
}
}
The first FOR loop check (which checks if the character is a space) works correctly. In the else, for characters that are not a space, it does not work correctly, since the corresponding character is not written to the output array
Sample program execution: