저는 Java에 익숙하지 않아 시저 암호 프로그램을 만들어야합니다. 이것은 내 코드입니다. 내가 겪고있는 문제는 내가 1 이상으로 그것을 바꿀 수 없다는 것이다. 예를 들어 'help me'라고 쓰고 2의 시프트 값을 입력하면 여전히 1만큼 이동한다. -> 'ifmq nf'칸트 시프트 시저 암호 하나 이상으로
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str;
String key;
int keyLength;
System.out.println("Enter message:");
str=sc.nextLine();
System.out.println("Enter encryption key:");
key=sc.next();
keyLength=key.length();
//This for loop is repeated use of 'Enrypt' and 'Decrypt' options
for(;;)
{
System.out.println("1.Encrypt\n2.Decrypt\n3.Exit...");
int choice=sc.nextInt();
switch(choice)
{
case 1:
/*send input string keyLength to encrypt() method to encrypt it returns 'Encrypted' string*/
System.out.println("Encrypted message..."+encrypt(str,keyLength));
break;
case 2:
//send retrived string from encrypt() method and keyLength to decrypt() method it returns 'Decrypted' string
System.out.println("Decryptedmessage..."+decrypt(encrypt(str,keyLength),keyLength));
break;
case 3:
//exit from the program
System.exit(0);
break;
default:
System.out.println("Invalid option..");
}
}
}
public static String encrypt(String str,int keyLength)
{
String encrypted="";
for(int i=0;i<str.length();i++)
{
//stores ascii value of character in the string at index 'i'
int c=str.charAt(i);
//encryption logic for uppercase letters
if(Character.isUpperCase(c))
{
c=c+(keyLength%26);
//if c value exceeds the ascii value of 'Z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
if(c>'Z')
c=c-26;
}
//encryption logic for lowercase letters
else if(Character.isLowerCase(c))
{
c=c+(keyLength%26);
//if c value exceeds the ascii value of 'z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'a' and 'z'
if(c>'z')
c=c-26;
}
//concatinate the encrypted characters/strings
encrypted=encrypted+(char) c;
}
return encrypted;
}
public static String decrypt(String str,int keyLength)
{
String decrypted="";
for(int i=0;i<str.length();i++)
{
//stores ascii value of character in the string at index 'i'
int c=str.charAt(i);
//decryption logic for uppercase letters
if(Character.isUpperCase(c))
{
c=c-(keyLength%26);
//if c value deceed the ascii value of 'A' increase it by adding 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
if(c<'A')
c=c+26;
}
//decryption logic for uppercase letters
else if(Character.isLowerCase(c))
{
c=c-(keyLength%26);
//if c value deceed the ascii value of 'A' increase it by adding 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
if(c<'a')
c=c+26;
}
//concatinate the decrypted characters/strings
decrypted=decrypted+(char) c;
}
return decrypted;
}
'시프트 값에
keyLength
의 모든 인스턴스를 변경하는 기억 하는가? '1'의 길이와'2'의 길이가 같으면'key'와 동일합니까 –'key.length()'는'String'의 길이를 돌려줍니다 (그래서'1'은 '1'과 '2'는 '1'등); 아마도 당신은'Integer.parse (key)'또는'Scanner # nextInt'를 사용해야 할 것입니까? – MadProgrammer
도움을 주셔서 대단히 감사합니다! – Jay