2017-05-22 1 views
0

사용자가 입력 한 단어를 암호화하고 해독 할 수있는 프로그램을 작성해야합니다. 할당 된 "암호화 키"를 사용합니다. 내가 원하는 것은 영문자 (예 : a = 1, b = 2, c = 3)와 비교하여 입력 된 키의 모든 문자의 가치를 확인한 다음 글자의 값을 더하는 것입니다. 그들이 지정한 단어의 문자를 이동하는 데 사용됩니다.for 루프에서 결과를 가져와 반복 할 때마다 다른 변수에 추가하십시오.

/* Validity Check from http://stackoverflow.com/questions/33965542/password-check-program-checking-capitals-lowercase-letters-digit-and-special 
* 
* 
* 
* 
*/ 
import java.util.*; 
public class SecretDecoderFinal 
{ 
    public static void main (String [] args) 
    { 
    optInput(); 

    } 

    public static int optInput() 
    { 
    int opt = 0; 
    do { 
     String word = ""; 
     String key = ""; 
     System.out.println("Welcome to Seegson Security secure transmission terminal"); 
     System.out.println(""); 
     System.out.println("Enter an option for the terminal"); 
     System.out.println("(1) to encrypt a word"); 
     System.out.println("(2) to decrypt a word"); 
     System.out.println("(0) to exit the terminal"); 
     opt = In.getInt(); 
     System.out.println("You selected: Option " +opt); 
     System.out.println(""); 
     switch(opt) 
     { 
     case 1: 
      encryptWord(word, key); 
      break; 
     case 2: 
      decryptWord(word, key); 
      break; 
     case 0: 
      System.out.println("Thank you for using the encryption/decryption program"); 
      break; 
     default: 
      System.err.println("Invalid option. Select 1 for encryption, 2 for decryption, or 0 to exit"); 
      System.out.println(""); 
      break; 
     } 
    }while (!isExit(opt)); 

    return opt; 

    } 

    public static String keyInput(String key) 
    { 


    do 
    { 
     System.out.println("Enter the key you want for encryption/decryption"); 
     key = In.getString(); 
     System.out.println("Your key is: " +key); 
     System.out.println(""); 

    }while (!isValid(key)); 
    //printEncrypted(key); 

    return key; 

    } 

    public static String wordInput(String word) 
    { 

    do 
    { 
     System.out.println("Enter the word you want decrypted/encrypted"); 
     word = In.getString(); 
     System.out.println("You entered: " +word); 
     System.out.println(""); 
    } while (!isValid(word)); 
    //printEncrypted(word); 
    return word; 

    } 

    public static void encryptWord(String word, String key) 
    { 
    // String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; 

    wordInput(word); 
    keyInput(key); 
    System.out.println("The word from the encryptWord metod " +word); 
    printEncrypted(word, key); 

    } 

    public static void decryptWord(String w, String k) 
    { 
    String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; 
    wordInput(w); 
    keyInput(k); 

    } 

코드의이 부분은 내 친구

public static String printEncrypted(String word, String key) 
    { 
    System.out.println("This is the word from the printEncrypted method: " +word); 

    int shift = 0; 

    //Uses the key length to determine how much the alphabet will shift 
    for (int x = 0; x < key.length(); x++) 

     shift += key.charAt(x) - 96; 
    shift = shift % 26; 


    //Creates an array to perform the shift 
    char [] y = word.toCharArray(); 

    for (int x = 0; x < y.length; x++) 
     //Uses the shift to shift the alphabet to decrypt the word. 
     for (int d = 0; d < shift; d++) 

     if (y[x] == 'z') 

     y[x] = 'a'; 

    else { 
     y[x]--; 
    } 
    String newWord = new String(y); 
    System.out.println("Encrypted is " +newWord); 
    return newWord; 


    } 

    public static boolean isValid (String s) 
    { 
    String strSpecialChars="[email protected]#$%&*()_+=-|<>?{}[]~"; 
    //String alphabet2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; 
    boolean upCase = false; 
    boolean isDigit = false; 
    boolean spChar = false; 

    if (s.matches(".+[A-Z].+")){ 
     upCase = true; 
    } 

    if (s.matches(".+[1-9].+")){ 
     isDigit = true; 
    } 

    if (strSpecialChars.contains(s)){ 
     spChar = true; 
    } 


    if (upCase|| isDigit || spChar) 

    { 
     System.err.println("The string cannot contain capital letters, special characters or numbers. Try again."); 
     System.out.println(""); 
     return false; 
    } 
    else 
    { 
     return true; 
    } 

    } 


    public static boolean isExit (int option) 
    { 
    if (option == 0) 
    { 

     return true; 
    } 
    else 
    { 
     return false; 
    } 
    } 

} 

을에서입니다 그리고 이것은 내 캐릭터 이동을 위해 할 노력하고 있어요 무엇 :

이 지금까지 내 할당 내가 가지고있는 코드입니다
public class LetterTester 
{ 
    public static void main (String []args) 
    { 

    String input="craig"; 
    final String alphabet="abcdefghijklmnopqrstvwxyz"; 
    int finalValue = 0; 
    int[] numbers; 
    for(int i=0;i<input.length();i++){ 

     finalValue=(alphabet.indexOf(input.charAt(i))+1); 
     System.out.print(finalValue); 

    } 

    } 
} 

그러나 변수를 작성하고 for 루프가 실행될 때마다 해당 출력을 변수에 추가하는 방법을 모르겠습니다. LetterTester는 테스트 용입니다. 나의 실제 임무에서, 입력은 다른 방법으로부터 취해지고 나서 테스트 될 것이다. 예를 들어, 키가 "abc"인 경우 a = 1, b = 2, c = 3 인 문자가 결정됩니다. 그런 다음이 변수를 함께 변수에 추가하려고합니다. 나는 사용할 수있다. 입력에 대한 계산이 끝나면 변수는 6이되어야합니다.

또한 두 번째 질문을해야할지 모르겠지만 할당을위한 코드에서 각각의 메서드 (keyInput 및 wordInput)에서 내 단어 및 키 입력 값을 전달할 수 없습니다. encryptWord라는 메서드에, encryptWord 메서드에서 테스트하려고하면 단어가 비어있는 것으로 표시됩니다.

사람이 내가 입력을 위해 무엇을했는지 궁금 경우, 나는 여기에서 얻은에서 클래스를 사용하고 있습니다 : 내 강사가를 사용하는 우리를 가르침으로써 처음부터 클래스를 가르쳤다

http://www.ecf.utoronto.ca/~jcarter/ 지금까지 수업에서.

+0

WRT에서'wordInput()'문제가 발생하면, 그 메소드의 반환 값에 무엇인가를 할당해야합니다 (예 : String wordToEncrypt = w ordInput();'. 매개 변수를 전달할 필요가 없습니다. 사용자로부터 입력을 읽고 값을 반환하기 때문입니다. – KevinO

+0

주석 처리 된 코드를 모두 포함시키는 목적이 무엇인지 이해하지 못합니다. 그리고 왜 이렇게 많은 여분의 빈 줄이 있습니까? 코드를 정리하십시오. –

+0

@KevinO 감사합니다! 나는 그것을 시도 할 것이다. –

답변

0

OP의 질문에 완전히 답하기에는 너무 많은 일이 있습니다. 다음 코드는 솔루션 공간에 대한 지침입니다.

  • 단어와 키의 입력을 서로 또는 다른 작업과 별도로 수집하십시오. getWord()getKey 메서드는 OP에서 언급 한대로 In 클래스를 사용해야합니다. 요점은 메소드가 매개 변수를 필요로하지 않고, 리턴을 가지며 정보 만 수집하기 (따라서 입력을 처리와 분리 함)입니다.
  • encryptWord(String, String) 메서드는 수집 된 입력을 가져 와서 어떤 방식으로 변환하여 변환을 반환합니다. 이 출력을 수행하지 않아야합니다 (다시, 처리와 별도의 입출력). 암호화 알고리즘을 복제하려고 시도하지 않았습니다.
  • decryptWord(String, String) 메서드는 수집 된 입력을 받아 알고리즘에 따라 변환합니다. 아무 것도 구현하려고 시도하지 않았지만 근본적으로 암호화의 반대입니다.
  • 실제로 모든 것이 정적이어야하는 것은 아니지만 OP의 방식을 따릅니다.
  • isValid(String)은 소문자만으로 제한됩니다. 분명히 가정이 맞지 않으면 조정할 수 있습니다.isValid()

    // 
    // is valid checks to see if only lower case characters 
    // 
    private static boolean isValid(final String chkWord) 
    { 
        // returns true only if the match is lower case a-z 
        return chkWord.matches("^[a-z]+$"); 
    } 
    
    private static String encryptWord(String word, String key) 
    { 
        // TODO: implement the encryption algorithm; 
        // The algorithm would use the key to do the encryption; 
        // here will just add to character as quick example 
        char[] wordChars = word.toCharArray(); 
    
        for (int i = 0; i < wordChars.length; ++i) { 
         char c = wordChars[i]; 
         if (c >= 'a' && c <= 'm') { c += 13; } 
         else if (c >= 'n' && c <= 'z') { c -= 13; } 
         wordChars[i] = c; 
        } 
    
        return new String(wordChars); 
    } 
    
    private static String decryptWord(String word, String key) 
    { 
        // TODO: implement the decryption algorithm 
        return "NEED TO IMPLEMENT"; 
    } 
    
    private static String getWord() 
    { 
        // the word should be gathered from the user in some fashion 
        // using the In class that is provided 
        return "helloworld"; 
    } 
    
    private static String getKey() 
    { 
        // the key should be gathered from the user in some fashion 
        // using the In class that is provided 
        return "doit"; 
    } 
    
    public static void main(String[] args) 
    { 
        final String word = getWord(); 
        final String key = getKey(); 
    
        boolean validWord = isValid(word); 
        System.out.printf("Is valid [%s]: %b%n", word, validWord); 
    
        if (! validWord) { 
        System.err.println("Not a good word!"); 
        return; 
        } 
    
        String encrypted = encryptWord(word, key); 
        System.out.printf("Encrypted %s: %s%n", word, encrypted); 
    
        String decrypted = decryptWord(word, key); 
        System.out.printf("Encrypted %s: %s%n", word, decrypted); 
    
    } 
    

빠른 검사 :

유효한가 [안녕하세요] : 거짓
유효 [안녕하세요]가 : 사실
가 유효 [specialchar *] : 거짓

+0

감사합니다. 나는 당신이 제안한 변경과 모든 것을 수행했다. (매개 변수와 메소드 호출은 잘 작동한다.) 암호화와 암호 해독은 잘 작동하지만 의도 한 방법이 아닙니다. 이것은 상당히 다르지만 나는 대답을 기다릴 것이다. 이것은 내 코드에서 가지고 있습니다. https://pastebin.com/4S3erBNH 제안 된 변경 사항을 적용 했으므로 유효성 검사기는 입력시 특수 문자 나 대문자와 같은 오류를 찾아 내지 못합니다 . –

+0

@AliHammad 전에는 잘 작동하고 있었고, 나는 그들이 원하는 암호화/암호 해독을 따르지 않았기 때문에 독자들에게 남겨진 운동이라고 말했습니다. 방금 장소 홀더를 갖기 위해 무언가를 던졌습니다. 귀하의 "친구"에서 가능성이 암호화 조각을 가지고 있지만 그것이 맞는지 아닌지 전혀 모르겠다. – KevinO

+0

@AliHammad, 위의'isValid()'메소드에 WRT : "Hello"= false; "hello"= true; "specialchar *"= false. 당신이보고있는 것을 확신하지 못합니다. – KevinO

관련 문제