Так что мой вопрос в том, когда я собираюсь скомпилировать мой класс TestCaesarCipherTwo, появляется сообщение об ошибке cannot find symbol variable dkey_0
. У меня есть dkey_0 в другом классе, а также в TestCaesarCipherTwo. Я чувствую, что где-то меня перепутал код, так что сразу вызывается так много методов. Dkey_0, вызывающий ошибку, находится в этой строке: System.out.println("Keys found: " + bct.dkey_0 + ", " + bct.dkey_1 + "\n" + broken);
.Невозможно найти символьную переменную dkey_0
Не мог бы кто-нибудь посмотреть, где я ошибся?
Вот код, где происходит ошибка:
import edu.duke.*;
/**
* Write a description of TestCaesarCipherTwo here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TestCaesarCipherTwo {
/**
* Calls two key encryption and decryption functions
* with test keys as defined in the exercise
*/
public void simpleTests()
{
int key1 = 17;
int key2 = 3;
FileResource fr = new FileResource();
String message = fr.asString();
CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(key1, key2);
String encrypted = cctk.encrypt(message);
System.out.println(encrypted);
String decrypted = cctk.decrypt(encrypted);
System.out.println(decrypted);
BreakCaesarTwo bct = new BreakCaesarTwo();
String broken = bct.decrypt(encrypted);
System.out.println("Keys found: " + bct.dkey_0 + ", " + bct.dkey_1 + "\n" + broken);
}
/**
* Selects and breaks any two key encrypted file.
* (So long as the most frequent letter is 'e')
*/
public void simplebreaker()
{
FileResource fr = new FileResource();
String encrypted = fr.asString();
BreakCaesarTwo bct = new BreakCaesarTwo();
String broken = bct.decrypt(encrypted);
System.out.println("Keys found: " + bct.dkey1 + ", " + bct.dkey2 + "\n" + broken);
}
public String breakCaesarTwo(String input) {
String in_0 = halfOfString(input, 0);
String in_1 = halfOfString(input, 1);
// Find first key
// Determine character frequencies in ciphertext
int[] freqs_0 = countOccurrencesOfLetters(in_0);
// Get the most common character
int freqDex_0 = maxIndex(freqs_0);
// Calculate key such that 'E' would be mapped to the most common ciphertext character
// since 'E' is expected to be the most common plaintext character
int dkey_0 = freqDex_0 - 4;
// Make sure our key is non-negative
if (dkey_0 < 0) {
dkey_0 = dkey_0+26;
}
// Find second key
int[] freqs_1 = countOccurrencesOfLetters(in_1);
int freqDex_1 = maxIndex(freqs_1);
int dkey_1 = freqDex_1 - 4;
if (freqDex_1 < 4) {
dkey_1 = dkey_1+26;
}
}
}
А вот код, где я пытаюсь позвонить BreakCaesarTwo (BCT) для линии System.out.println("Keys found: " + bct.dkey_0 + ", " + bct.dkey_1 + "\n" + broken);
:
public class BreakCaesarTwo{
private String alphabetLower;
private String alphabetUpper;
private String shiftedAlphabetLower1;
private String shiftedAlphabetUpper1;
private String shiftedAlphabetLower2;
private String shiftedAlphabetUpper2;
private int mainKey1;
private int mainKey2;
public String encrypt(String input) {
StringBuilder encryptedInput = new StringBuilder(input);
OOCaesarCipher oocc1 = new OOCaesarCipher(mainKey1);
OOCaesarCipher oocc2 = new OOCaesarCipher(mainKey2);
for (int index=0; index < input.length(); index++) {
if (index % 2 == 0 || index == 0) {
encryptedInput.replace(index,index+1,oocc1.encrypt(input.substring(index,index+1)));
}
else {
encryptedInput.replace(index,index+1,oocc2.encrypt(input.substring(index,index+1)));
}
}
return encryptedInput.toString();
}
public String halfOfString(String message, int start) {
StringBuilder halfString = new StringBuilder();
for (int index=start;index < message.length();index += 2) {
halfString.append(message.charAt(index));
}
return halfString.toString();
}
public int[] countOccurrencesOfLetters(String message) {
//snippet from lecture
String alph = "abcdefghijklmnopqrstuvwxyz";
int[] counts = new int[26];
for (int k=0; k < message.length(); k++) {
char ch = Character.toLowerCase(message.charAt(k));
int dex = alph.indexOf(ch);
if (dex != -1) {
counts[dex] += 1;
}
}
return counts;
}
public int maxIndex(int[] values) {
int maxDex = 0;
for (int k=0; k < values.length; k++) {
if (values[k] > values[maxDex]) {
maxDex = k;
}
}
return maxDex;
}
public String breakCaesarTwo(String input) {
String in_0 = halfOfString(input, 0);
String in_1 = halfOfString(input, 1);
// Find first key
// Determine character frequencies in ciphertext
int[] freqs_0 = countOccurrencesOfLetters(in_0);
// Get the most common character
int freqDex_0 = maxIndex(freqs_0);
// Calculate key such that 'E' would be mapped to the most common ciphertext character
// since 'E' is expected to be the most common plaintext character
int dkey_0 = freqDex_0 - 4;
// Make sure our key is non-negative
if (dkey_0 < 0) {
dkey_0 = dkey_0+26;
}
// Find second key
int[] freqs_1 = countOccurrencesOfLetters(in_1);
int freqDex_1 = maxIndex(freqs_1);
int dkey_1 = freqDex_1 - 4;
if (freqDex_1 < 4) {
dkey_1 = dkey_1+26;
}
CaesarCipherTwoKeys cctk = new CaesarCipherTwoKeys(dkey_0, dkey_1);
return cctk.decrypt(input);
}
public String decrypt(String input) {
CaesarCipherTwoKeys cctk= new CaesarCipherTwoKeys(26 - mainKey1, 26 - mainKey2);
String decrypted = cctk.encrypt(input);
return decrypted;
}
}
Я могу» t выяснить, почему я получаю эту ошибку. dkey_0 уже включен в оба класса (BreakCaesarTwo и TestCaesarCipherTwo). Я пытался добавить методы Пустоты SimpleTests и SimpleBreaker, когда я получил эту ошибку.
В качестве дополнительной заметки: Цель этой программы - шифровать, расшифровывать и распечатывать сообщение, дешифрованное вместе с двумя ключами, которые в качестве альтернативы расшифровывают сообщение.
Любая помощь была бы принята с благодарностью, спасибо.
Должен ли я добавить его чуть ниже, где я объявляю класс TestCaesarCipherTwo? – user5745776
Вы должны добавить эту переменную 'dkey_0' так же, как у вас есть' mainKey1' в классе 'BreakCaesarTwo'. Конечно, инкапсулируйте эту переменную. –
Должен ли я инициализировать 'dkey_0' в BreakCaesarTwo или в TestCaesarCipherTwo? Потому что наличие этого в BreakCaesarTwo не помогает. – user5745776