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 =...
I keep getting this error, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for...
I keep getting this error, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0    at simpleInheritance/simpInher.Dwelling$DriverTest.main(Dwelling.java:146) Can someone help me fix it? import java.io.BufferedReader;    import java.io.FileNotFoundException;    import java.io.FileReader;    import java.util.*;    import java.io.*;    import java.io.FileWriter;    import java.io.IOException;    class Dwelling {    /*    Declaring Variables    */    String streetAddress;    String city;    String state;    String zipCode;    int bedrooms;    double bathrooms;       /*   ...
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) {       ...
Can anyone fix this code? The code isn't rounding the answer to the nearest whole number...
Can anyone fix this code? The code isn't rounding the answer to the nearest whole number like 2.345 should be 2 and 2.546 should be 3 but the round() function isn't working as expected. The round() function is rounding 2.546 to 2 which is incorrect since 4 and below should be rounded to 2 and 5 and above should be rounded to 3. Here is the code: #importing xlwt library to write into xls import xlwt from xlwt import Workbook...
Can you fix my code and remove the errors? Thank you!! ^^ ////////////////////////////////////////////////////////////////////////////////////////////////////// public class StackException<T,...
Can you fix my code and remove the errors? Thank you!! ^^ ////////////////////////////////////////////////////////////////////////////////////////////////////// public class StackException<T, size> extends Throwable { private final T[] S = null ; public StackException(String s) { } public T top() throws StackException { if (isEmpty()) throw new StackException("Stack is empty."); int top = 0; return S[top]; } private boolean isEmpty() { return false; } public T pop() throws StackException { T item; if (isEmpty()) throw new StackException("Stack underflow."); int top = 0; item = S[top];...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT