7 Replies - 4293 Views - Last Post: 18 March 2013 - 07:26 PM Rate Topic: -----

#1 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 11:01 AM

It's on line 29. When I call changeShiftValue(1) it prints out the letters but the value after z in the array is "temp" so that says the value was never changed. Also if I call the method with "7" as the parameter it will get that arrayindexoutofbounds error. I have no idea what I did wrong.

import java.util.Arrays;


public class CaesarShiftEncryption {
	
	private static final 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"};
	private static String[] eAlphabet = new String[ALPHABET.length]; //Encrypted alphabet
	static {Arrays.fill(eAlphabet, "temp");}
	private static int shiftValue;
	private static final int LIMIT = ALPHABET.length;
	
	public static String changeShiftValue(int shift) {
		
		if (shift > LIMIT - 1 || shift <= 0)
			shiftValue = 1;
		else
			shiftValue = shift;
		
		//^ If a number over 25 or under 1 is entered, the shift will default to 1
		
		int temp = 0;
		for (int i = 0; i < LIMIT - 1; i++) {
			
			temp = i + shiftValue;
			if (temp > LIMIT) {
				temp = temp - LIMIT - 1;
			}
			
			eAlphabet[i] = ALPHABET[temp];
			
		}
		
		StringBuilder cipher = new StringBuilder();
		cipher.append("Shift value changed to " + shiftValue + " and the new alphabet = {");
		for (int i = 0; i < LIMIT; i++) {
			if (i == LIMIT - 1)
				cipher.append(eAlphabet[i]);
			else
				cipher.append(eAlphabet[i] + ", ");
		}
		cipher.append("}");
		
		return cipher.toString();
		
	}
	
	public static String encryptMessage(String msg) {
		
		StringBuilder encryptedMessage = new StringBuilder();
		
		for (char c : msg.toCharArray()) {
			
			if (c == ' ') {
				encryptedMessage.append(" ");
			} else {
				
				for (int i = 0; i < LIMIT - 1; i++) {
					if (ALPHABET[i].equalsIgnoreCase(new String(new char[] {c})))
						encryptedMessage.append(eAlphabet[i]);
				}
				
			}
			
		}
		
		return "Encrypted message: " + encryptedMessage;
		
	}

}



Also, in the main class after someone enters the shift value the program will terminate and just print "Encryption Message: ". Did I do something wrong? I mostly use the Scanner class to read files so I'm not that good at user input. And I know the exit method in the main class looks stupid but I was just lazy on that part so I put that there temporarily.

import java.util.Scanner;


public class CaesarShiftTester {
	
	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		
		System.out.print("Enter 1 to encrypt or 2 to decrypt a message: ");
		int choice = 0;
		choice = in.nextInt();
		if (choice > 2 || choice < 1) choice = 1;
		
		if (choice == 1) {
			
			System.out.print("\nMessage Encrypter\nPlease enter a shift value or -1 to quit (for example a shift value of 1 will make a = b [You can enter a shift value from 1 to 25]): ");
			int shiftValue = in.nextInt();
			if (shiftValue == -1) exit(in);
			System.out.println("\n" + CaesarShiftEncryption.changeShiftValue(shiftValue));
			in.reset();
			
			System.out.println("Please enter your message to encrypt or -1 to quit: ");
			String msg = in.nextLine();
			if (msg.equals("-1")) exit(in);
			
			System.out.println("\n" + CaesarShiftEncryption.encryptMessage(msg) + "\n");
			
		} else {
			
			
			
		}
		
	}
	
	//I was to lazy to write a few lines of code so I did this
	
	private static void exit(Scanner s) {
		s.close();
		System.exit(0);
	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: Caesar Cipher ArrayIndexOutOfBounds Exception

#2 guido-granobles   User is offline

  • D.I.C Addict
  • member icon

Reputation: 171
  • View blog
  • Posts: 617
  • Joined: 02-December 09

Re: Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 11:50 AM

I haven't seen the whole code but you should try this:
if (temp > (LIMIT - 1)) {
        temp = (temp - LIMIT) - 1;
}



you should sorround the operators with brackets to determine the order of the operations.
Was This Post Helpful? 0
  • +
  • -

#3 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 12:03 PM

if (temp > LIMIT) {

should be

if (temp >= LIMIT) {

There is a much easier way to do that

String alphabet = "abcdefghijklmnopqrstuvwxyz";

String shifted = alphabet + alphabet;

if the user enters 'c'
char x = 'c';
simply do
int index = 'c' - 'a' + shift;
char coded = shifted.charAt(index);

This post has been edited by pbl: 18 March 2013 - 12:09 PM
Reason for edit:: alphabet not just alpha

Was This Post Helpful? 1
  • +
  • -

#4 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3648
  • View blog
  • Posts: 16,770
  • Joined: 20-September 08

Re: Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 01:12 PM

http://technojeeves....-cipher-in-java
Was This Post Helpful? 1
  • +
  • -

#5 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 06:39 PM

View Postpbl, on 18 March 2013 - 11:03 AM, said:

if (temp > LIMIT) {

should be

if (temp >= LIMIT) {

There is a much easier way to do that

String alphabet = "abcdefghijklmnopqrstuvwxyz";

String shifted = alphabet + alphabet;

if the user enters 'c'
char x = 'c';
simply do
int index = 'c' - 'a' + shift;
char coded = shifted.charAt(index);


How would I decrypt it? I don't understand how your method works. Would it be 'a' - c + shift or c - 'a' - shift?

Edit: Sorry for the message pbl, I didn't realize you were in this thread when I was writing it.

This post has been edited by The_Programmer-: 18 March 2013 - 06:48 PM

Was This Post Helpful? 0
  • +
  • -

#6 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 07:00 PM

The letters in the ASCII table have a value

a == 97
b == 98
...
z == 122

so if your shift is +4 and the user enters 'c'

'c' which is 99 - 'a' which is 97 == 2 so the letter is the third one in the alphabet (thisrd one because we start to count at 0 so a-0 b-1 c-2

So 2 + shift 4 gives 6 and shifted.charAt(6) is: 'g'

abcdefghij
0123456789

we concatenate 2 alphabet so if the user enter 'z'
'z' - 'a' is
122 - 97 = 25 make sense + the shift 4 = 29 to shifted.charAt(29) is 'd'

zabcdef
2222233
5678901

Now to convert back... yes we will have to apply -shift
but this number may be negative so add 26 to the value
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
we add 26 to start here   ^


so if code letter is 'c'
'c' - 'a' = 2 less the shift 4 = -2 we add 26 so 24 so 'y'

so

char encode(char x) {
   int index = x - 'a';
   index += shift;
   return shifted.charAt(index);
}

char decode(char x) {
   int index = x - 'a';
   index -= shift;
   index += 26;
   return shicted.charAt(index);
}



Happy coding (in both sense of the word :))
Was This Post Helpful? 1
  • +
  • -

#7 The_Programmer-   User is offline

  • Paranormal Investigator
  • member icon

Reputation: 25
  • View blog
  • Posts: 694
  • Joined: 24-October 11

Re: Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 07:21 PM

Thanks! I get it now.
Was This Post Helpful? 0
  • +
  • -

#8 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Caesar Cipher ArrayIndexOutOfBounds Exception

Posted 18 March 2013 - 07:26 PM

Glad I could help.

Now if you want to pursue in Secret Code you'll go to the Vigenere code with is Tutorial #2 of my 9 Secret Code tutorials

http://www.dreaminco...igenere-square/
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1