【发布时间】:2014-04-24 11:28:02
【问题描述】:
我正在尝试开发一种替换密码,它使用关键字来创建新的密码字母表。我是 Java 新手(我相信你会知道的!),我正在找到它 很难将我的头脑围绕在我需要做的代码上。
我的理解如下:
例如,如果关键字是javben,我应该首先在plainText字符串数组中找到“j”的索引,即9。然后我想将plainText[9]转换为cipherText[0 ] 并将其他元素移动 1。因此,这的第一遍将导致:
cipherText[] = {"j","a","b","c","d","e","f","g","h","i","k","l","m","n","o","p","q","r","s","t","u","v","w","r","x","y","z"}
然后我会找到“a”,它已经在它应该在的位置,所以我需要考虑到这一点,而不是改变它——不知何故。下一个字符是“v”,因此该过程将继续。
在转换密码中的所有内容后,我应该得到:
plainText []= {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","r","x","y","z"}
cipherText[]= {"j","a","v","b","e","n","c","d","f","g","h","i","k","l","m","o","p","q","r","s","t","u","w","r","x","y","z"}
正如您所看到的,我有理由确定我了解要经历的过程,但是我真的很难将我的头脑围绕在此所需的代码上。请帮忙!
import java.util.Scanner;
import java.io.*;
/**
* This program uses a keyword for a simple substitution cipher.
*
* @author Bryan
* @version Programming Project
*/
public class Cipher
{
// The main method removes duplicate characters in a word input by the user.
public static void main(String[] args) throws IOException
{
// Creatae a new scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// prompt the user to enter a word
System.out.println("Please enter your keyword: ");
// and get their input
String input = keyboard.nextLine();
// the keyword will be built up here
String keyword = "";
while(input.length() > 0)
{
// get the first letter
char letter = input.charAt(0);
// if the letter is not already in the output
if (keyword.indexOf(letter) == -1)
{
// add it to the end
keyword = keyword + letter;
}
// that letter is processed : discard it
input = input.substring(1);
}
//this is just to confirm the duplicate letters in the keyword are removed
System.out.println(keyword);
getFile();
}
/**
* This asks the user to specify a filename which is then
* read into the program for enciphering
*/
public static void getFile()throws IOException
{
// Creatae a new scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Get the file name
System.out.println("Enter the file name: ");
String filename = keyboard.nextLine();
//Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read the lines from the file until no more are left
while (inputFile.hasNext())
{
//Read the next line
String allText = inputFile.nextLine();
// Display the text
System.out.println(allText);
}
//Close the file
inputFile.close();
}
public static void alphabet()
{
String[] plainText = {"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"};
String[] cipherText = {"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"};
}
}
【问题讨论】:
-
你的过程太复杂了。为什么不简单地获取您的关键字(javben),然后附加字母表中的每个字母(a、b、c...),除非它包含在关键字中?
-
这是很好的建议,确实帮助我简化了问题。谢谢!
标签: java encryption keyword substitution