删除多余的字母,然后将字符串声明为charArr

时间:2017-04-29 20:57:06

标签: java string

我正在尝试使用带有随机关键字的密文来加密和解密字符串。随机关键字将位于文件“keyword.txt”中:

TROYONLINE

字符串将位于单独的文件“input.txt”中:

THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG
more lines here....

密码应使用关键字和反向字母而不包含多余字母。关键字“TROYONLINE”的密码为:

TROYNLIEZXWVUSQPMKJHGFDCBA

使用此密码,上述字符串将加密为:

HEN MGZOW RKQDS LQC XGUPNY QFNK HEN VTAB YQI

到目前为止,我有这段代码:

import java.util.*;
import java.io.*;

public class reverseString
{
   public static void main(String [] args)
   {
      String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      String cipher = "";
      String newCipher;
      String encrypt = "";
      String ouput = "";

      BufferedReader readerKeyword = null;
      String key = "";
      try 
      {
          readerKeyword = new BufferedReader(new FileReader("keyword.txt"));          
      }
      catch (FileNotFoundException fnfex)
      {
         System.out.println(fnfex.getMessage() + " File not found.");
         System.exit(0); 
      }
      try
      {
         while ((key = readerKeyword.readLine()) !=null)
         {
           StringBuffer sb = new StringBuffer();

         int len = abc.length();

         for(int i = len -1;i>=0;i--)
              cipher = cipher + abc.charAt(i);

         newCipher = sb.append(key).append(cipher).toString();
         System.out.println(key);
         System.out.println(removeDuplicates(newCipher));

         }
      }
      catch (IOException ioex)
      {
         System.out.println(ioex.getMessage() + " Unable to read file.");
         System.exit(0);
      }

       BufferedReader readerInput = null;
        String lineInput;

       try 
       {
              readerInput = new BufferedReader(new FileReader ("input.txt"));           
       }
       catch (FileNotFoundException fnfex)
       {
         System.out.println(fnfex.getMessage() + " File not found.");
         System.exit(0); 
       }
       try
       {
          while ((lineInput = readerInput.readLine()) !=null)
          {
           char[] inputArray = lineInput.toCharArray();
           System.out.println(inputArray);
          }
       }
       catch (IOException ioex)
       {
         System.out.println(ioex.getMessage() + " Unable to read file.");
       }
   }

   static String removeDuplicates(String newCipher)
   {
      char[] charArr = newCipher.toCharArray();
      Set<Character> charSet = new LinkedHashSet<Character>();
      for(char ch : charArr)
      {
         charSet.add(ch);
      }
      StringBuffer StrBuf = new StringBuffer();
      for(char c : charSet)
      {
         StrBuf.append(c);

      }

      char[] cipherArray = removeDuplicates(newCipher).toCharArray();
      System.out.println(cipherArray);
      return StrBuf.toString();
   }
}

但我收到以下错误:

TROYONLINE
Exception in thread "main" java.lang.StackOverflowError
    at java.util.HashMap.<init>(HashMap.java:456)
    at java.util.LinkedHashMap.<init>(LinkedHashMap.java:347)
    at java.util.HashSet.<init>(HashSet.java:161)
    at java.util.LinkedHashSet.<init>(LinkedHashSet.java:154)
    at reverseString.removeDuplicates(reverseString.java:83)
    at reverseString.removeDuplicates(reverseString.java:94)

最后一行的重复次数......(reverseString.java:94)

2 个答案:

答案 0 :(得分:0)

修改

在我们的情况下,我会如何做到这一点。但要记住这一点:

  1. 将密钥和输入文本放在文件中是没有意义的。如果您有很多输入行,那么您将把密钥作为命令行参数传递,并且只有一个while循环读取输入文件并使用相同的密钥进行加密和解密。如果你有多个键,那么你需要读取每个键然后逐行读取整个输入文件,然后读取下一个键并再次读取输入文件等等。
  2. 我掌握了main方法中的所有逻辑,但是你应该将它分解为单独的方法。
  3. 主要课程:

    String defaultAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    BufferedReader keyInputLine;
    String key;
    String cipher = "";
    BufferedReader inputLine;
    String inputText;
    StringBuilder encryptedText;
    StringBuilder decryptedText;
    
    try {
        keyInputLine = new BufferedReader(new FileReader("keyword.txt"));
    
        while ((key = keyInputLine.readLine()) != null) {
            System.out.println("key: " + key);
    
            StringBuilder stringBuilder = new StringBuilder();
    
            // cipher is the key word plus the reverse of the alphabet
            cipher = stringBuilder.append(key).append(new StringBuilder(defaultAlphabet).reverse().toString()).toString();
    
            System.out.println("cipher: " + cipher);
    
            // remove duplicates from cipher
            cipher = removeDuplicates(cipher);
    
            System.out.println("replaced cipher: " + cipher);
        }
    
        inputLine = new BufferedReader(new FileReader("input.txt"));
    
        while ((inputText = inputLine.readLine()) != null) {
            System.out.println("original: " + inputText);
    
            encryptedText = new StringBuilder();
    
            for (char c : inputText.toCharArray()) {
                // find the input letter in the alphabet
                if (defaultAlphabet.indexOf(c) != -1) {
                    // replace with same index from the cipher
                    encryptedText.append(cipher.toCharArray()[defaultAlphabet.indexOf(c)]);
                } else {
                    // if not found, use default (ex: space)
                    encryptedText.append(c);
                }
            }
    
            System.out.println("encrypted: " + encryptedText.toString());
    
            decryptedText = new StringBuilder();
    
            for (char c : encryptedText.toString().toCharArray()) {
                // find the encrypted letter in the cipher
                if (cipher.indexOf(c) != -1) {
                    // replace with same index from the cipher
                    decryptedText.append(defaultAlphabet.toCharArray()[cipher.indexOf(c)]);
                } else {
                    // if not found, use default (ex: space)
                    decryptedText.append(c);
                }
            }
    
            System.out.println("decrypted: " + decryptedText.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    删除重复方法:

    static String removeDuplicates(String cipher) {
        Set<Character> charSet = new LinkedHashSet<Character>();
    
        for (char ch : cipher.toCharArray()) {
            charSet.add(ch);
        }
    
        StringBuilder stringBuilder = new StringBuilder();
    
        for (char c : charSet) {
            stringBuilder.append(c);
        }
    
        return stringBuilder.toString();
    }
    

    上一个答案

    就像错误所说的那样,&#34; lineKeyword&#34;变量在使用前未初始化。考虑到第二次尝试/捕获可能存在异常。捕获异常并打印消息但是&#34; lineKeyword&#34;仍然没有初始化。

    这里有一个很好的答案:Uninitialized variables and members in Java

      

    语言以这种方式定义它。

         

    对象类型的实例变量默认为初始化为null。默认情况下,对象类型的局部变量未初始化,并且访问未定义的变量是编译时错误。

         

    请参阅此处的{4.5}部分http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html#96595

答案 1 :(得分:0)

我最终将我的密码放在BufferedReader代码的while循环中,并将其清除。

{
      BufferedReader readerKeyword = null;
      String key = "";
      try 
      {
          readerKeyword = new BufferedReader(new FileReader("keyword.txt"));          
      }
      catch (FileNotFoundException fnfex)
      {
         System.out.println(fnfex.getMessage() + " File not found.");
         System.exit(0); 
      }
      try
      {
         while ((key = readerKeyword.readLine()) !=null)
         {
         StringBuffer sb = new StringBuffer();

         int len = abc.length();

         for(int i = len -1;i>=0;i--)
              cipher = cipher + abc.charAt(i);

         newCipher = sb.append(key).append(cipher).toString();
         System.out.println(key);
         System.out.println(removeDuplicates(newCipher));

         }
      }
      catch (IOException ioex)
      {
         System.out.println(ioex.getMessage() + " Unable to read file.");
         System.exit(0);
      }