有两个类:
key.java和test.java
在test.java中,预期结果是ascii值a + 5 = f?哪个会输出但是当我运行它时:
System.out.println(k1.encode('G')); // expected output 'L'
输出不是G加5的ascii值,它输出:小写e?
我在这里达到了我的门槛,为什么?
key.java:
class Key{
private int value;
Key(int value){
this.value = value;
}
public char encode(char c){
if (isValidKey(value) == true) {
if (c >= 'a' && c <= 'z'){
c = (char)(( c - 'a' + value) % 26 + 'a');
}else if (c >= 'A' && c <= 'Z'){
c = (char)(( c - 'A' + value) % 26 + 'A');
}else if (c >= '0' && c <= '9'){
c = (char)(( c - '0' + value) % 10 + '10');
} else {
return '.';
}
return c;
}
public char decode(char c){
if (isValidKey(value) == true) {
if (c >= 'a' && c <= 'z'){
c = (char)(( c - 'a' - value) % 26 + 'a');
}else if (c >= 'A' && c <= 'Z'){
c = (char)(( c - 'A' - value) % 26 + 'A');
}else if (c >= '0' && c <= '9'){
c = (char)(( c - '0' - value) % 10 + '10');
}else{
return'.';
}
return c;
}
public static boolean isValidKey(int value){
if (value >= 0 && value <= 25){
return true;
} else {
return false;
}
}
}
}
}
test.java:
public class Test{
public static void main(String[] args) {
Key k1,k2;
k1=new Key(5);
k2=new Key(15);
String s="This is a test. Let's see if that works";
String t=Cryptic.encrypt(s,k1);
System.out.println("Original: "+s);
System.out.println("Encoded with k1: "+t);
System.out.println("The result ddecoded with k1: "+Cryptic.decrypt(t,k1));
//individual tests
System.out.println(Key.isValidKey(5)); // the expected output is true
System.out.println(Key.isValidKey(25)); // the expected output is true
System.out.println(Key.isValidKey(-1)); // the expected output is false
System.out.println(Key.isValidKey(-10)); // the expected output is false
System.out.println(Key.isValidKey(200)); // the expected output is false
System.out.println(Key.isValidKey(1)); // the expected output is true
Key k3= new Key(-1);
System.out.println(k1.encode('a')); // expected output 'f'
System.out.println(k2.encode('a')); // expected output 'p'
System.out.println(k1.encode('7')); // expected output '2'
System.out.println(k3.encode('a')); // expected output '.'
System.out.println(k3.encode('7')); // expected output '.'
System.out.println(k1.decode('a')); // expected output 'v'
System.out.println(k2.decode('a')); // expected output 'l'
System.out.println(k1.decode('7')); // expected output '2'
System.out.println(k3.decode('a')); // expected output '.'
System.out.println(k3.decode('7')); // expected output '.'
System.out.println(k1.encode('G')); // expected output 'L'
System.out.println(k1.decode('G')); // expected output 'B'
System.out.println(k1.encode('*')); // expected output '*'
}
}
答案 0 :(得分:0)
试试这个......
public char encode(char c){
if (isValidKey(value) == true) {
if (c >= 'a' && c <= 'z'){
c = (char)(( c - 'a' + value) % 26 + 'a');
}else if (c >= 'A' && c <= 'Z'){
c = (char)(( c - 'A' + value) % 26 + 'A');
}else if (c >= '0' && c <= '9'){
c = (char) ( c + value);
if(c>57)
c-=10;
}
} else {
return '.';
}
return c;
}