Hello, I'm trying to program a Caesar Cipher, but I keep getting weird errors. My input is not being handled correctly. I have no idea, i've tried different variations, but it does not work, here is my code.
import java.io.*;
import java.util.Scanner;
public class CaesarCipher
{
public static final int SIZE = 52;
public static final char[] 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', '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'};
protected char[] coded = new char[SIZE];
protected char[] decoded = new char[SIZE];
public int CaesarCipher()
{
for (int i = 0; i < SIZE; i++)
{
coded[i] = alphabet[(i + 3) % SIZE];
}
for(int i = 0; i < SIZE; i++)
{
decoded[coded[i] - 'A'] = alphabet[i];
}
return 0;
}
public String encode(String secret)
{
char[] message = secret.toCharArray();
for (int i = 0; i < message.length; i++)
{
if(Character.isUpperCase(message[i]))
{
message[i] = coded[message[i] - 'A'];
}
}
return new String(message);
}
public String decode(String secret)
{
char[] message = secret.toCharArray();
for (int i = 0; i < message.length; i++)
{
if(Character.isUpperCase(message[i]))
{
message[i] = decoded[message[i] - 'A'];
}
}
return new String(message);
}
public static void main(String[] args)
{
CaesarCipher cipher = new CaesarCipher();
System.out.printf("Caesar Cipher! \n");
System.out.println("\nPlease enter message: ");
Scanner input = new Scanner(System.in);
String phrase = " ";
while(input.hasNextLine())
{
phrase = input.next();
}
phrase = cipher.encode(phrase);
System.out.println(phrase);
phrase = cipher.decode(phrase);
System.out.println(phrase);
}
}
It will print out the first 2 phrases like Caesar Cipher and please enter text, I have it when I enter text, but i'm assuming the while loop won't break, but when I hit enter to continue the program it just goes to a new line. If I remove the while loop I get the no such element error. How can I handle my input, should an exception be thrown? Thanks in advance for your help.