How do I generate random characters between each character in a string?… here is a solution to the problem.
How do I generate random characters between each character in a string?
I have a
code where I have to implement an interface with the goal of getting a string, like mycookisred
, and inserting random characters from the original word in it. In this case, this can hinder, for example, Meynciovoksidswrbendn
. Another example, for completeness: the mycleverpassword
string can be turned into mxyschlmezvievrppeaysisvwcoorydc
.
I know my code isn’t exactly fit for this purpose, but can someone help or guide me on what to do from this starting point?
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();
}
Solution
Just use it to randomize and normalize strings:
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;
}
Classes should start with uppercase characters. You don’t need to, but Eclipse will cry, for example.