Question

In: Computer Science

Can you fix the code and comment the fix Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -39 at...

Can you fix the code and comment the fix

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -39
        at CaesarCipher.encrypt(CaesarCipher.java:28)
        at CaesarCipher.main(CaesarCipher.java:52)

public class CaesarCipher{

    char[] encoder = new char[52];
    char[] decoder = new char[52];

     public CaesarCipher(int rotation)
     {
       for(int k=0 ; k < 26 ; k++)
       {
           encoder[k] = (char) ('A' + (k + rotation) % 26);
           decoder[k] = (char) ('A' + (k - rotation + 26) % 26);
       }
       for(int j = 26 ; j < 52 ; j++ )
       {
           encoder[j] = (char)('a' + (j + rotation) % 26);
           decoder[j] = (char)('a' + (j - rotation) % 26);
       }
     }

     public String encrypt(String message) {
         char[] msg = message.toCharArray();
         for(int i = 0 ; i < msg.length ; i++){
            if(Character.isUpperCase(msg[i])){
                msg[i] = encoder[msg[i] - 'A'];
            }
            else{
                int n = msg[i] - 'a' ;
                msg[i] = encoder[26 + n];
            }
         }
         return new String(msg);
     }

     public String decrypt(String secret) {
        char[] msg = secret.toCharArray();
         for(int i = 0 ; i < msg.length ; i++){
            if(Character.isUpperCase(msg[i])){
                msg[i] = decoder[msg[i] - 'A'];
            }
            else{
                 int n = msg[i] - 'a';
                msg[i] = decoder[26 + n];
            }
         }
         return new String(msg);
     }


public static void main(String[] args) {
    CaesarCipher cipher = new CaesarCipher(3);
    String message = "There Is an APPle";
    String coded = cipher.encrypt(message);
    System.out.println("Secret: " + coded);
    String answer = cipher.decrypt(coded);
    System.out.println("Message: " + answer);       
}
}

Solutions

Expert Solution

`Hey,

Note: If you have any queries related to the answer please do comment. I would be very happy to resolve all your queries.

Your code was not accounting for space actually caesar cipher rotates the alphabets not the spaces

Below is the updated

public class CaesarCipher{

char[] encoder = new char[52];
char[] decoder = new char[52];

public CaesarCipher(int rotation)
{
for(int k=0 ; k < 26 ; k++)
{
encoder[k] = (char) ('A' + (k + rotation) % 26);
decoder[k] = (char) ('A' + (k - rotation + 26) % 26);
}
for(int j = 26 ; j < 52 ; j++ )
{
encoder[j] = (char)('a' + (j + rotation) % 26);
decoder[j] = (char)('a' + (j - rotation) % 26);
}
}

public String encrypt(String message) {
char[] msg = message.toCharArray();
for(int i = 0 ; i < msg.length ; i++){
if(Character.isUpperCase(msg[i])){
msg[i] = encoder[msg[i] - 'A'];
}
else if(Character.isLowerCase(msg[i])){
int n = msg[i] - 'a' ;
msg[i] = encoder[26 + n];
}
}
return new String(msg);
}

public String decrypt(String secret) {
char[] msg = secret.toCharArray();
for(int i = 0 ; i < msg.length ; i++){
if(Character.isUpperCase(msg[i])){
msg[i] = decoder[msg[i] - 'A'];
}
else if(Character.isLowerCase(msg[i])){
int n = msg[i] - 'a';
msg[i] = decoder[26 + n];
}
}
return new String(msg);
}


public static void main(String[] args) {
CaesarCipher cipher = new CaesarCipher(3);
String message = "There Is an APPle";
String coded = cipher.encrypt(message);
System.out.println("Secret: " + coded);
String answer = cipher.decrypt(coded);
System.out.println("Message: " + answer);   
}
}

Kindly revert for any queries

Thanks.


Related Solutions

I keep get this exception error Exception in thread "main" java.lang.NullPointerException    at Quadrilateral.returnCoordsAsString(Quadrilateral.java:44)    at...
I keep get this exception error Exception in thread "main" java.lang.NullPointerException    at Quadrilateral.returnCoordsAsString(Quadrilateral.java:44)    at Quadrilateral.toString(Quadrilateral.java:51)    at tester1.main(tester1.java:39) In this program I needed to make a Point class to create a coordinate square from x and y. I also needed to make a Quadrilateral class that has an instance reference variable to Point .The Quadrilateral class then inherits itself to other classes or in this case other shapes like square, trapazoid. I thought I did it right but...
when i run the program on eclipse it gives me this error: Exception in thread "main"...
when i run the program on eclipse it gives me this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0    at SIM.main(SIM.java:12) how do I fix that ? (please fix it ) import java.util.*; import java.util.Scanner; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import java.lang.Math; public class SIM{    public static void main(String[] args) throws FileNotFoundException {       int cacheSize = Integer.parseInt( args[1] ); int assoc = Integer.parseInt( args[2] ); int replacement = Integer.parseInt(...
I'm getting this error: Exception in thread "main" java.lang.NoSuchMethodError: main I tried using public static void...
I'm getting this error: Exception in thread "main" java.lang.NoSuchMethodError: main I tried using public static void main(String[] args){ but that negates all of the methods that I try to write. I'm just trying to make it so that I can enter values. Thanks. Code below: import java.util.Scanner; public class DataSet2 { private double value; private double sum; private int count; public void add(double value){    System.out.println("Enter values, enter -1 to finish");    Scanner scan = new Scanner(System.in);    value =...
Why am I getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds...
Why am I getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at HW3.main(HW3.java:6) The code: import java.io.FileWriter; import java.io.IOException; public class HW3 { public static void main(String[] args) throws IOException { // 0th argument contains the name of algorithm String algo = args[0]; // 1st argument contains the name of file // Make a new file FileWriter fw = new FileWriter(args[1]); if (algo.equals("p1")) { // 2nd argument comes in the form of...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
Can you fix this code please. the removing methods id no doing anything. this is java...
Can you fix this code please. the removing methods id no doing anything. this is java code import java.util.NoSuchElementException; public class DoublyLinkedList<E> {    public int size;    public Node head;    public Node tail;             @Override    public boolean isEmpty() {               return size == 0;    }    @Override    public int getSize() {               return 0;    }    @Override    public void addAtFront(E element) {       ...
Need to fix this code for tc -tac-toe game .. see the code below and fix...
Need to fix this code for tc -tac-toe game .. see the code below and fix it #include <iostream> using namespace std; void display_board(); void player_turn(); bool gameover (); char turn ; bool draw = false; char board [3][3] = { {'1', '2', '3'}, { '4', '5', '6'}, { '7', '8', '9'}}; int main() { cout << " Lets play Tc- Tac- toe game " <<endl ; cout << " Player 1 [X] ----- player 2 [0] " <<endl <<endl;...
Thread Programming (C Programming) Objective Develop threads: thread and main. Functionality of Threads: The main program...
Thread Programming (C Programming) Objective Develop threads: thread and main. Functionality of Threads: The main program accepts inputs from the user from the console. The user can provide the following two types of input: add num1 num2 mult num1 num2 Here, num1 and num2 are two integer numbers. E.g., the user may input add 1 2. The threads receive the command along with the number, and performs the appropriate arithmetic operation and returns the results to main program. The main...
Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class...
Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class Main { static int comparisons; static int exchanges; // Recursive function to perform insertion sort on sub-array arr[i..n] public static void insertionSort(int[] arr, int i, int n) { int value = arr[i]; int j = i; // Find index j within the sorted subset arr[0..i-1] // where element arr[i] belongs while (j > 0 && arr[j - 1] > value) { arr[j] = arr[j...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT