我有一个代码,我必须在其中实现一个接口,目的是采用一个mycookisred
之类的字符串,并在其中将随机字符插入原始单词的每个字符之间。在这种情况下,这可能会阻碍meynciovoksidswrbendn
。为了完整起见,另一个示例:mycleverpassword
字符串可以变成mxyschlmezvievrppeaysisvwcoorydc
。
我知道我的代码不完全适合该目的,但是有人可以从这个起点帮助或指导我做什么吗?
import java.util.Random;
public class password implements Encryptable
{
private String message;
private boolean encrypted;
private int shift;
private Random generator;
public password(String msg)
{
message = msg;
encrypted = false;
generator = new Random();
shift = generator.nextInt(10) + 5;
}
public void encrypt()
{
if (!encrypted)
{
String masked = "";
for ( int index = 0; index < message.length(); index++)
masked = masked + (char)(message.charAt(index) +shift);
message = masked;
encrypted = true;
}
}
public String decrypt()
{
if (!encrypted)
{
String unmasked = "";
for ( int index = 0; index < message.length(); index++)
unmasked = unmasked + (char)(message.charAt(index) - shift);
message = unmasked;
encrypted = false;
}
return message;
}
public boolean isEncrypted()
{
return encrypted;
}
public String toString()
{
return message;
}
}
public class passwordTest
{
public static void main(String[] args)
{
password hide = new password("my clever password");
System.out.println(hide);
hide.encrypt();
System.out.println(hide);
hide.decrypt();
System.out.println(hide);
}
}
public interface Encryptable
{
public void encrypt();
public String decrypt();
}
答案 0 :(得分:3)
只需使用它来随机化和标准化字符串:
private String randomize(String s) {
String re = "";
int len = s.length();
for(int i = 0; i < len - 1; i++) {
char c = s.charAt(i);
re += c;
re += (char) (generator.nextInt('z' - 'a') + 'a');
}
re += s.charAt(len - 1);
return re;
}
private String normalize(String s) {
String re = "";
for(int i = 0; i < s.length(); i+=2) {
re += s.charAt(i);
}
return re;
}
并且Class应该以大写字母开头。您不需要,但是例如Eclipse会哭。