I am learning how to use arrays and I want to write a method that takes the given array(The alphabet), encrypts the array based on a formula, and prints the new array. My code is as follows:
import java.util.Scanner;
public class Encryption {
public static void main(String[] args){
String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
Scanner in = new Scanner(System.in);
System.out.println("Please select a number from 0-25: ");
int key = in.nextInt();
System.out.println(encryption(alphabet,key));
}
public static String[] encryption(String[] alphabet, int key){
String[] newalph = new String[25];
int alpha = 0;
for(String a: alphabet){
if ((0 <= a.indexOf(a) + key) && (a.indexOf(a) + key< 26)){
newalph[alpha] = alphabet[a.indexOf(a) + key];
alpha++;
}
else if ( a.indexOf(a) + key >= 26){
newalph[alpha] = alphabet[((a.indexOf(a)) + key) - 26];
alpha++;
}
}
return newalph;
}
}
I suspect that it's something inside the for loop but I'm not entirely sure.