1
I’m making a program to encrypt according to Caesar’s Cipher in Java. I came across the following problem in 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 Else, for characters that are not a space, it does not work correctly, since the output array does not save the corresponding character
Example of implementation of the programme:
Looking at your code around here, I realized that the first
if
within the secondfor
wherepalavraGerada[i] == alphabet[j]
the "wordGerada" in its "i" position is always blank, so it will never be the same as its alphabet. It would not be the place to put thepalavraLida
?– Paulo H. Hartmann