Question: ****Using java eclipse please fix my coding for the following problem. My coding starts over when you get to A or Z and we are
****Using java eclipse please fix my coding for the following problem. My coding starts over when you get to A or Z and we are suppose to "assume that the shift never goes past the beginning or end of the alphabet". So please fix the coding to make it not go before A or after Z.****
Problem: Write a program called CaesarLite that encodes a message using a Caesar cipher. The user should be prompted for the number of positions to shift (positive or negative) and a message to encode. For example, a shift of 3 would map A to D and B to E. You can assume that only capital letters need to be shifted and that other characters will not be changed. For this version, ***you can assume that the shift never goes past the beginning or end of the alphabet.***
Example output 1: Enter shift: 4 Enter message: HELLO Encoded message: LIPPS
Example output 2: Enter shift: -1 Enter message: IbM 9000 Encoded message: HbL 9000
Here is my code for this problem that needs fixing:
import java.util.Scanner;
import java.util.*;
public class CaesarLite {
public static String encode(String[] message1, int shift) {
String s1 = "";
for (int j = 0; j < message1.length; j++) {
String word = message1[j];
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (c >= 'A' && c <= 'Z' && (char) (c + shift) >= 'A' && (char) (c + shift) <= 'Z') {
s1 += (char) (c + shift);
} else if ((char) c + shift > 'Z' && c >= 'A' && c <= 'Z') {
s1 += (char) (c - (26 - shift));
} else if ((char) c + shift < 'A' && c > '9' && c >= 'A' && c <= 'Z') {
s1 += (char) (c + (26 + shift));
} else {
s1 += c;
}
}
if (j < message1.length - 1)
s1 += " ";
}
return "The Encoded message is : " + s1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter shift :");
int shift = sc.nextInt();
sc.nextLine();
System.out.println("Enter the message:");
String[] message = sc.nextLine().split(" ");
System.out.println(CaesarLite.encode(message, shift));
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
