我有一个代码,我必须在其中实现一个接口(interface),目的是获取一个字符串,如 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();
}
最佳答案
只需使用它来随机化和规范化字符串:
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;
}
类应该以大写字符开头。您不需要,但例如 Eclipse 会哭。
关于java - 如何在字符串中的每个字符之间生成随机字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398578/