我正在尝试为大学项目创建一个Cipher程序,我能够创建密码,但我无法对其进行编码。我的代码在下面,有人可以引导我朝着正确的方向前进吗?前两种方法都可以,主要是我遇到问题的最后两种方法。这是我第一个参加任何编程的学期,所以我对它很陌生。
import java.util.Scanner;
import java.util.Random;
public class Cipher
{
public static void main (String[] args){
System.out.print("Please type a sentence to be encrypted\n");
Scanner inputScanner = new Scanner(System.in);
String input = inputScanner.next();
input = input.toLowerCase();
char[] inputArray=input.toCharArray();
inputScanner.close();
char[] alphabetArray = {' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q'
,'r','s','t','u','v','w','x','y','z'};
char[] cipherArray = alphabetArray.clone();
createCipher(cipherArray);
encrypt(alphabetArray, inputArray, cipherArray);
for(int index=0; index<alphabetArray.length; index++)
{
System.out.print(alphabetArray[index]);
}
System.out.print("\n");
for(int index2=0; index2<cipherArray.length; index2++)
{
System.out.print(cipherArray[index2]);
}
System.out.print("\nYour encrypted message is:\n");
for(int index3=0; index3<inputArray.length; index3++)
{
System.out.print(inputArray[index3]);
}
System.out.print("\n");
decrypt(alphabetArray, inputArray, cipherArray);
for(int index4=0;index4<inputArray.length; index4++)
{
System.out.print(inputArray[index4]);
}
}
public static void createCipher( char[] alphabet )
{
if (alphabet!=null)
{
Random generator = new Random();
for (int index=0; index<alphabet.length; index++ )
{
int otherIndex = generator.nextInt(alphabet.length);
char temp = alphabet[index];
alphabet[index] = alphabet[otherIndex];
alphabet[otherIndex] = temp;
}
}
}
public static void encrypt(char[] alphabet, char[] input, char[] cipher)
{
if(input!=null)
{
for(int index =0; index<input.length; index++)
{
for(int index2 =0; index2<alphabet.length; index2++)
{
if(input[index]==alphabet[index2])
{
input[index]=cipher[index2];
}
}
}
}
}
public static void decrypt(char[] alphabet, char[] encryptedInput, char[] cipher)
{
if(encryptedInput!=null)
{
for(int index =0; index<encryptedInput.length; index++ )
{
for(int index2=0; index2<cipher.length; index2++)
{
if(encryptedInput[index]==cipher[index2])
{
encryptedInput[index]=alphabet[index2];
}
}
}
}
}
}
答案 0 :(得分:1)
在这个方法中
public static void encrypt(char[] alphabet, char[] input, char[] cipher)
{
if(input!=null)
{
for(int index =0; index<input.length; index++)
{
for(int index2 =0; index2<alphabet.length; index2++)
{
if(input[index]==alphabet[index2])
{
input[index]=cipher[index2];
}
}
}
}
}
您需要在语句return;
之后键入input[index]=cipher[index2];
您应该在decrypt()方法中执行相同的操作。然后你的程序应该没问题。现在,您是否也可以手动执行错误的代码,并告诉我为什么需要返回语句?