Write a cencrypt() function that takes a arbitrary length string and an integer as inputs and returns a string as output.
The cencrypt() function you write in lab today needs to work on strings that contain upper-case letters, lower-case letters, or both. The output string should be all upper-case letters. (The Romans of Caesar's time used only what today we call upper-case letters.)
So a call to cencrypt("Caesar", 1) should return (return not print) the string “DBFTBS” and a call to cencrypt(“DBFTBS”, -1)should return the string "CAESAR".
The string function .upper() mentioned in the assigned reading in Chapter 7.3 of Zybooks that gives back a version of its string that has all alphabet characters converted to upper case may be useful here.
CODE IN JAVA:
Cencrypt.java file:
import java.util.Arrays;
public class Cencrypt {
public static String cencrypt(String input,int n)
{
input = input.toUpperCase();
int len = input.length();
int temp;
char arr[]=new char[len];
for(int i=0;i<len;i++) {
temp =
charToInt(input.charAt(i))+n;
if(temp>26)
temp = temp - 26;
else
if(temp<1)
temp = temp + 26;
arr[i] =
intToChar(temp);
}
return Arrays.toString(arr)
.substring(1, 3*arr.length-1)
.replaceAll(", ", "");
}
//method to get corresponding character
static char intToChar(int n) {
char alpha[] =
{'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'};
return alpha[n-1];
}
//method to get corresponding integer
static int charToInt(char ch) {
char alpha[] =
{'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'};
for(int i=0;i<alpha.length;i++)
{
if(alpha[i]==ch)
{
return i+1;
}
}
return 0;
}
public static void main(String[] args) {
String input = "Caesar";
System.out.println("The input
string is:"+input);
//calling the methods and
displaying the result
String output =
cencrypt(input,1);
System.out.println("After calling
the cencrypt method with n=1 the output is:"+output);
String temp =
cencrypt(output,-1);
System.out.println("After calling
the cencrypt method with n=-1 the output is:"+temp);
}
}
OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.