Reputation: 193
I am almost finished with a program that takes user input and encrypts the message then displays it back. For some reason I am unable to pass the string to my encryption method and return it. Does anyone see where I have gone wrong?
Thank you so much to anyone who responds!
public static String doEncryption(String s)
{
char 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' };
char key[] = { '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', 'a' };
char encoded[] = new char[(s.length())];
String encrypted="";
int j=0;
for(int i=0; i<s.length(); i++){
//System.out.println(s.charAt(i));
boolean isFound = false;
j = 0;
while (j < alphabet.length && !isFound){
if (alphabet[j]==s.charAt(i)){
encrypted=encrypted+key[j];
isFound=true;
}
j++;
}
if(j>=alphabet.length){
encrypted=encrypted+s.charAt(i);
}
}
return (new String(encrypted));
}
public static void main(String args[])
{
String match = "QUIT";
String en = "";
System.out.println("Welcome to the Encoding Program!");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the text you want encoded below. Type QUIT when finished. ");
en = sc.nextLine();
String trim = en.substring(0, en.indexOf("QUIT"));
doEncryption(trim.toLowerCase());
//String en = doEncryption(sc.nextLine().toLowerCase());
System.out.println("The text is encoded as: " + trim.toUpperCase());
sc.close();
}
}
Upvotes: 0
Views: 84
Reputation: 21004
Simply because you never re-assign the value.
Change
doEncryption(trim.toLowerCase());
to
trim = doEncryption(trim.toLowerCase());
then System.out.println("The text is encoded as: " + trim.toUpperCase());
will display the correct value.
Beware of this line
en.substring(0, en.indexOf("QUIT"));
It will throw a java.lang.StringIndexOutOfBoundsException
if "QUIT" is not in the string.
I think you want the program to execute until "QUIT" is entered so you need to loop over until the input is "QUIT". Your main method would look like this
String match = "QUIT";
String en = "";
System.out.println("Welcome to the Encoding Program!");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the text you want encoded below. Type QUIT when finished. ");
do
{
en = sc.nextLine();
if(!en.toUpperCase().equals(match))
{
en = doEncryption(en.toLowerCase());
System.out.println("The text is encoded as: " + en.toUpperCase());
}
} while(!match.equals(en.toUpperCase()));
sc.close();
When you want to exit, simply input quit.
Upvotes: 2
Reputation: 1074425
Your method returns the updated string, so you'll want to use that return value when calling it. Change:
doEncryption(trim.toLowerCase());
to
String updatedValue = doEncryption(trim.toLowerCase());
or reuse trim
if you like:
trim = doEncryption(trim.toLowerCase());
...and then use updatedValue
or trim
to show the result.
Upvotes: 2