第一次来这里。我正在尝试编写一个程序,该程序从用户获取字符串输入并使用replaceFirst方法对其进行编码。除“。”(严重重音)外的所有字母和符号都能正确编码和解码。
e.g。当我输入
`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");
}
}
}
我已经尝试将转义字符放在重音符号前面,但它仍然没有正确编码。
答案 0 :(得分:2)
看看你的程序在每次循环迭代中的工作原理:
i=0
encryptThis = '12
(我用'而不是'来更容易地写这篇文章)i=1
1
所以2812
- &gt; 28AA2
i=2
2
所以2
替换为BB
2812
- &gt; BB8AA2
尝试使用来自appendReplacement
类Matcher
类的java.util.regex
{/ 1}}
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();
}
答案 1 :(得分:0)
encryptThistemp.substring(i, i + 1);
子字符串的第二个参数是长度,您确定要增加i
吗?因为这意味着在第一次迭代后test
不会是1个字符长。这可能会抛弃我们看不到的的其他情况!