2013-07-30 34 views
-2

第一次来这里。我试图编写一个程序,它接受来自用户的字符串输入并使用replaceFirst方法对其进行编码。除“`”(格雷夫重音)以外的所有字母和符号都可以正确编码和解码。replaceFirst字符 “`”

例如当我输入

`12 

我应该得到28AABB作为我的加密,而是,它给了我BB8AA2

public class CryptoString { 


public static void main(String[] args) throws IOException, ArrayIndexOutOfBoundsException { 

    String input = ""; 

    input = JOptionPane.showInputDialog(null, "Enter the string to be encrypted"); 
    JOptionPane.showMessageDialog(null, "The message " + input + " was encrypted to be "+ encrypt(input)); 



public static String encrypt (String s){ 
    String encryptThis = s.toLowerCase(); 
    String encryptThistemp = encryptThis; 
    int encryptThislength = encryptThis.length(); 

    for (int i = 0; i < encryptThislength ; ++i){ 
     String test = encryptThistemp.substring(i, i + 1); 
     //Took out all code with regard to all cases OTHER than "`" "1" and "2" 
     //All other cases would have followed the same format, except with a different string replacement argument. 
     if (test.equals("`")){ 
      encryptThis = encryptThis.replaceFirst("`" , "28"); 
     } 
     else if (test.equals("1")){ 
      encryptThis = encryptThis.replaceFirst("1" , "AA"); 
     } 
     else if (test.equals("2")){ 
      encryptThis = encryptThis.replaceFirst("2" , "BB"); 
     } 
    } 
} 

我试图把转义字符的重音的前面,但是,它仍然没有正确编码。

+3

你真的有一个'else'没有' if'? –

+2

你的代码不能编译。发布您正在使用的真实代码会更有帮助。 – Pshemo

+0

我删除了所有其他情况,只显示这个特定的情况。 – user2635709

回答

0

encryptThistemp.substring(i, i + 1);子的第二个参数是长度,你确定要被增加i?因为这意味着在第一次迭代test后不会有1个字符长。这可能会甩掉我们看不到的其他情况

2

看看你的程序在每次循环迭代是如何工作的:

    • i=0
    • encryptThis = '12(我用'而不是'来更容易写这个帖子)
    • 现在你替换'28,所以它会变成2812
    • i=1
    • 我们在位置1读取的字符,这是1所以
    • 我们用AA制备2812替换1 - >28AA2
    • i=2
    • 我们在2位读取的字符,它是如此2
    • 我们替换杉ST2BB使2812 - >BB8AA2

尽量使用可能从appendReplacementMatcherjava.util.regex包像

public static String encrypt(String s) { 
    Map<String, String> replacementMap = new HashMap<>(); 
    replacementMap.put("`", "28"); 
    replacementMap.put("1", "AA"); 
    replacementMap.put("2", "BB"); 

    Pattern p = Pattern.compile("[`12]"); //regex that will match ` or 1 or 2 
    Matcher m = p.matcher(s); 
    StringBuffer sb = new StringBuffer(); 

    while (m.find()){//we found one of `, 1, 2 
     m.appendReplacement(sb, replacementMap.get(m.group())); 
    } 
    m.appendTail(sb); 

    return sb.toString(); 
}