Reputation: 33
I'm trying to create a program in java which will replace(encode/decode) characters of a given input (string) with different characters. So far Ive written some code for the encoding part but it doesn't seem to work and I'm unsure why.
This is the encode part of the Key class, consider that the isValidKey works.
public Key (int value){
}
public char encode(char c){
if (isValidKey(value) == true){
int x = (int)c + value;
c = (char)x;
return c;
}else{
return '.';
}
}
This is the encrypt part of the Cryptic class.
public static java.lang.String encrypt(java.lang.String s, Key k){
for (int i =0; i<s.length(); i++) {
char x = s.charAt(i);
char c = k.encode(x);
s = s.replace(x,c);
}
return s;
}
This all compiles but when I test it, it simply doesn't do anything at all, to the given input (string).
What I want to achieve is that when the value of they Key is set to for e.g 5 the input of 'a' would change to 'f'.
This is the isValidKey method
public static boolean isValidKey(int value){
if (value >= 0 && value <= 25)
return true;
else
return false;
}
The variable decelerations in the Key class
public class Key {
private int value;
private int c;
Upvotes: 2
Views: 95
Reputation: 538
There's a bit of code I'd like to see: the variable declarations in your Key
class. The comment from Dragondraikk is probably the clue you need. My bet is that you've got a class level var called value
of type int
, right? So you need the following in your Key
constructor:
this.value = value;
I suspect your encode()
method only returns dots at the moment. If that's the case, this should fix it.
Upvotes: 0
Reputation: 311978
String
s in Java are immutable. String.replace
does not alter the original string, but rather returns a new String
with the characters replaced.
So, instead of:
s.replace(x,c);
You should have:
s = s.replace(x,c);
Upvotes: 4