public class encryption {
public static void main(String[] args) {
System.out.print(encrypt("Peach"));
}
//accepts a string and returns the string in reverse
public static String reverse(String s){
String result = "";
for (int i = 0; i < s.length(); i++) {
result = s.charAt(i) + result;
}
return result;
}
//accepts a string and returns an encrypted version of that string
public static String encrypt(String s) {
String str = "";
int length = str.length();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
c = (char)(c - 20);
str += c;
str = (reverse(str));
}
length = str.length();
str = str.charAt(length - 1) + str.substring(1, length-1) + str.charAt(0);
System.out.println( "encrypt Not Yet Implemented." );
return str;
}
}
ecryption code working but not sure if it's 100%
Page 1 of 12 Replies - 793 Views - Last Post: 31 October 2014 - 01:11 PM
#1
ecryption code working but not sure if it's 100%
Posted 31 October 2014 - 12:21 PM
This is the encryption code I wrote for an assignment, and it is working as it should I believe.. however in the assignment he says that "The String, Peach, encrypts to: <OMQT" I am getting this "OM<QT" which is very close.. but I'm not sure if I am doing anything wrong. The assignment asked to use the following algorithm: 1. subtract 20 from numeric coe of each character. 2. reverse the resulting string. 3. swap first an last characters.
Replies To: ecryption code working but not sure if it's 100%
#2
Re: ecryption code working but not sure if it's 100%
Posted 31 October 2014 - 12:59 PM
I have seen a problem and tested your code and now it is working! The problem is because you have to reverse the whole thing, not reverse each char. Here is the code below:
I hope this helped
public class encryption {
public static void main(String[] args) {
System.out.print(encrypt("Peach"));
}
// accepts a string and returns the string in reverse
public static String reverse(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
result = s.charAt(i) + result;
}
return result;
}
// accepts a string and returns an encrypted version of that string
public static String encrypt(String s) {
String str = "";
int length = str.length();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
c = (char) (c - 20);
str += c;
}
str = (reverse(str));
length = str.length();
str = str.charAt(length - 1) + str.substring(1, length - 1)
+ str.charAt(0);
System.out.println("encrypt Not Yet Implemented.");
return str;
}
}
I hope this helped
#3
Re: ecryption code working but not sure if it's 100%
Posted 31 October 2014 - 01:11 PM
It did ! I actually just realized I had reverse in my loop on accident right before I read this! Thank you for your response though!
Page 1 of 1

New Topic/Question
Reply


MultiQuote


|