I have written a program that encrypts and decrypts a file that gets read in using a foursquare cipher. Currently, I am storing the file to a character array, passing that into a function which breaks it up into bigrams, and encrypting it that way using nested for loops in another function. At this point, I'm basically trying to optimize the running time. Is there an alternative way to iterate through the two-dimensional array I'm using that doesn't use two for loops or, at the most, using only one for loop? Below is the relevant code:
FileHandler.java
import java.io.*;
import java.util.*;
public class FileHandler {
private List<String> characters = new ArrayList<String>();
public char fileToChar[];
public void preEncryptionFile(String fileText) throws IOException {
String line;
FileInputStream fileReader = new FileInputStream(fileText);
DataInputStream dataInputStream = new DataInputStream(fileReader);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(dataInputStream));
while ((line = bufferedReader.readLine()) != null) {
characters.add(line);
}
String charsToString = characters.toString();
charsToString = charsToString.replaceAll("[^a-zA-Z]", "").toUpperCase();
fileToChar = charsToString.toCharArray();
bufferedReader.close();
}
}
FourSquareCipher.java
import java.util.*;
public class FourSquareCipher {
List<Character> encryptionList = new ArrayList<Character>();
List<Character> decryptionList = new ArrayList<Character>();
private char[][] matrix = {
{ 'A', 'B', 'C', 'D', 'E', 'Z', 'G', 'P', 'T', 'F' },
{ 'F', 'G', 'H', 'I', 'K', 'O', 'I', 'H', 'M', 'U' },
{ 'L', 'M', 'N', 'O', 'P', 'W', 'D', 'R', 'C', 'N' },
{ 'Q', 'R', 'S', 'T', 'U', 'Y', 'K', 'E', 'Q', 'A' },
{ 'V', 'W', 'X', 'Y', 'Z', 'X', 'V', 'S', 'B', 'L' },
{ 'M', 'F', 'N', 'B', 'D', 'A', 'B', 'C', 'D', 'E' },
{ 'C', 'R', 'H', 'S', 'A', 'F', 'G', 'H', 'I', 'K' },
{ 'X', 'Y', 'O', 'G', 'V', 'L', 'M', 'N', 'O', 'P' },
{ 'I', 'T', 'U', 'E', 'W', 'Q', 'R', 'S', 'T', 'U' },
{ 'L', 'Q', 'Z', 'K', 'P', 'V', 'W', 'X', 'Y', 'Z' } };
public void encryptionBigram(char[] fileToText) {
int i;
char x, y;
for (i = 0; i < fileToText.length - 1; i += 2) {
x = fileToText[i];
y = fileToText[i + 1];
encryption(x, y);
}
}
private void encryption(char x, char y) {
int i, j;
int a, b, c, d;
a = b = c = d = 0;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (x == matrix[i][j]) {
a = i;
b = j;
}
}
}
for (i = 5; i < 10; i++) {
for (j = 5; j < 10; j++) {
if (y == matrix[i][j]) {
c = i;
d = j;
}
}
}
encryptionList.add(matrix[a][d]);
encryptionList.add(matrix[c][b]);
}
}