Java:如何创建一个通过交换字符对来加密行的程序?

时间:2016-10-28 03:03:04

标签: java encryption

我正在寻找一种简单的编码程序的方法,该程序通过交换字符对来加密行,并且这些字符由用户输入。例如,如果你写了以下任何一个:

Original line         Encrypted line
abcdef                badcfe
The quick brown fox   hT euqci krbwo nofx
abc                   bac

我只能实现这样的简单加密:

import java.util.Scanner;
public class Encryption
{
public static void main(String[] args){
    Scanner kb = new Scanner(System.in);
    System.out.println("enter a line");
    String line = kb.nextLine();
    String encrypted="";
    for (int i=0; i<line.length(); i++){
        char c = line.charAt(i);
        if (c == 'a')
            encrypted += 'e';
        else if (c == 'e')
            encrypted += 'a';
        else 
            encrypted += c;
    }
    System.out.println(encrypted);
}

可以修改它以执行交换对加密吗?

1 个答案:

答案 0 :(得分:0)

这可能有用......

public class Test {

    public static void main(String[] args){

        Scanner kb = new Scanner(System.in);
        System.out.println("enter a line");
        String line = kb.nextLine();

        String encrypted = encriptInput(line);

        System.out.println(encrypted);
    }

    private static String encriptInput(String line) {

        String[] splitedChars = line.split("(?<=\\G.{2})");
        String outPut = "";

        for (int i = 0; i < splitedChars.length; i++) {

            outPut = splitedChars[i].trim().length() < 2?outPut+splitedChars[i]:outPut+splitedChars[i].charAt(1)+splitedChars[i].charAt(0);
        }

        return outPut;
    }
}