Ошибка печати символа Java Caesar Shift - PullRequest
0 голосов
/ 14 сентября 2018

Я пытаюсь работать над очень простой программой (к которой я позже добавлю), чтобы выполнить Цезарь Сдвиг для введенного пользователем текста.

У меня много работает, но когда я пытаюсь распечатать "зашифрованную" строку, она не работает. Я использую Netbeans IDE, и он просто печатает пустое значение. Я добавил дополнительные операторы печати к проверке ошибок, и я считаю, что мое «шифрование» - то есть изменение символов происходит правильно, но когда я преобразовываю его в символ, что-то не получается. Мой код ниже:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package forpractice;
import java.util.*;
import java.util.Scanner;

class CaesarShift {

//    public String encrypt(String[] plainText){
//        return null;
//        
//        
//        
//    }

    public static void main(String[] args){

        // Variable declarations needed for the entire program
        Scanner myScan = new Scanner(System.in);
        System.out.println("Please input a string of characters to encrypt: ");
        String plainText = myScan.nextLine();
        String convertedText = plainText.toLowerCase();
        char[] plainTextArray = convertedText.toCharArray();
        ArrayList<Character> encryptedTextArray = new ArrayList<>();
        String encryptedString = new String();


        int currValue;
        char curr;
        char curr1;
        char newCurr;
        int newCurrValue;
        // Variable declarations needed for the entire program

        // Loop through the array, convert to all lowercase, and encrypt it
        for (int i = 0; i < plainTextArray.length; i++){
            curr = plainTextArray[i];
            System.out.println("Current character: " + plainTextArray[i]);
            currValue = (int) curr;
            System.out.println("Current character value: " + currValue);
            newCurrValue = ((currValue-3) % 26);
            System.out.println("Encrypted character value: " + newCurrValue);
            newCurr = (char) newCurrValue;
            System.out.println("Encrypted character: " + newCurr);
            encryptedTextArray.add(newCurr);

        } //end for

        System.out.println("Here is the algorithm :");
        System.out.println("***************");
        System.out.println("Your Plaintext was: " + plainText);

        System.out.println("Your encrypted text was: ");
        for (int i = 0; i < encryptedTextArray.size(); i++){
            encryptedString += encryptedTextArray.get(i);
        }

        System.out.println("***************");


    } //end psvm       
} //end class

Буду очень признателен за любые ваши советы или пожелания. Я не нашел никаких примеров с этой конкретной проблемой. Спасибо.

1 Ответ

0 голосов
/ 14 сентября 2018

Обратите пристальное внимание на таблицу Ascii и ваше выражение

newCurrValue = ((currValue-3) % 26);

Вы вычитаете 3 из текущего значения и берете мод 26 после этого, что гарантирует, что ваш результат находится в пределахграницы от 0 до 26. Если вы посмотрите на это в таблице, вы обнаружите, что нет ни значений от a до z, ни значений от A до Z.На самом деле все эти символы либо невидимы, либо не заполнены.

В следующем примере демонстрируется правильное использование строчных букв:

newCurrValue = ((currValue - 'a') % 26 - 3); // 3 is your shift value

// if the result is negative, simply add 26 (amount of smallercase characters)
if (newCurrValue < 0) {
    newCurrValue += 26;
}
newCurrValue += 'a'; // add 'a' again, to be within 'a' - 'z'

Кроме того, несмотря на небольшую ошибку, вы не увидели быВ любом случае результат на консоли, так как вы пропустили оператор журнала:

System.out.println("Your encrypted text was: ");
for (int i = 0; i < encryptedTextArray.size(); i++) {
    encryptedString += encryptedTextArray.get(i);
}
System.out.println(encryptedString); // output your result
...