Reputation: 9
I'm trying to write a program that takes an input file password, encrypts it, then saves it to another file while still encrypted. So far I've gotten the program to create the file and for each letter in the password it will replace the letter. The problem is for each letter in the password, I'm printing out the password instead of a character of the alphabet.I want to take my password "fallout" and for each letter change is to a different random letter. Like "fallout" to "dfljsor" for example. I believe the problem is with my print line, how do I fix it?
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WriteFile {
public static void main(String [] args) throws IOException {
java.io.File inputFile = new java.io.File("inputFile.txt");
java.io.File outputFile = new java.io.File("encrypted.txt");
//create files and write to files
try(Scanner input = new Scanner(inputFile);
PrintWriter output = new PrintWriter(outputFile);) {
//creating array that holds the abc's
//password is tombraider
String key[] = { "q","w","r","t","u","i","o",
"p","a","s","d","f","g","h",
"j","k","l","z","x","c","v",
"b","n","m" };
String key1[] = { "qwertyuiopasdfghjklzxcvbnm" };
while (input.hasNext()) {
String x = input.nextLine();
//select a random char in key
double number = Math.random() * 27;
String index = key1.toString();
char sort = index.charAt((int) number);
// for each letter in the password, it is to be replaced with sort
for (int i = 0; i < x.length(); i++) {
char select = ((char) i);
output.print(x.replace(select, sort));
}
}
}
}
}
Upvotes: 0
Views: 77
Reputation: 776
I don't have high enough rep to comment (which I meant to). But it seems you are using x.replace(select, sort)
. You have set x
to an entire line. What you probably intended to do was something like Character.toString(x.charAt(i)).replace(select, sort))
or of the sort. That way you get each character, instead of the entire line.
Upvotes: 1