I am new to Java and this a very basic question. This is a very small part of the program. Here is what I have to do:
User inputs a number (1-26) in keyLength
as an encryption. If number is 1, secretletter
would be a; if its 2 it would be b, and so on until z where it will be 26.
What I want to know is that, is there a better way than doing this:
if (keyLength==1){
secretletter=a;
if (keyLength==2){
secretletter=b;
What I have done is below, but my for loop is wrong and I always end up with z.
public static char secret(String str,int keyLength){
char secretletter = 0;
if (keyLength>=0 && keyLength<27){
for(char i='a'; i<='z';i++){
secretletter=i;
}
}
return secretletter;
}
EDIT: I found my mistake and @that other guy helped me as well
secretletter=(char)('a'+ keyLength - 1);
You may want to take a look at Oracle documentation for the switch statement.
public static char secret(int keyLength){
char key;
switch (keyLength) {
case 1: key = 'a';
break;
case 2: key = 'b';
break;
case 3: key = 'c';
break;
........
default: key = 'z';
break;
}
return key;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.