如何在Java中创建随机生成的字母 [英] how to create a random generated alphabet in Java
问题描述
试图为替换密码创建随机生成的字母.我的想法是这样的.
Looking to create a randomly generated alphabet for a substitution cipher. My idea was something like this.
char randomChar = (char) (97 + r.nextInt(25));
但是,这将导致字母重复.遍历char数组并查看该字母是否已经存在似乎也是无效的.
However this will cause repetition of letters. Going through the char array and seeing if the letter is already present seems inefficient also.
edit:我的要求太含糊了,现在看看.这是我要解决的完整问题.字母还必须包含空格键字符,例如''.
edit: I was too vague in my request and see this now. Here is the full question I am trying to solve. The alphabet must also contain the space button character e.g ' '.
编写一个Java程序,该程序使用替代密码(将纯文本字母随机分配给密文字母)将(用户输入的)纯文本转换为密文.请注意,替换密码"将明文替换为密文.最常见的替换密码将明文的单个字符替换为预定义的密文单个字符(例如,纯文本字符"a"可能会替换为密文字符"q","b"可能会替换为"x","c"乘"k",依此类推).每个纯文本字符应替换为不同的密文字符.作为解决方案的一部分,您必须至少编写和使用以下函数/方法:(i)createCipher(),它确定并返回从纯文本到密文的映射.每个纯文本字符('a'..'z','')必须随机分配一个密文字符;
Write a Java program which converts (user entered) plain text to cipher text using a substitution cipher (in which plain text letters are randomly assigned to cipher text letters). Note that a Substitution Cipher replaces plaintext with cipher-text. The most common substitution ciphers replace single characters of plaintext with predefined single characters of cipher-text (e.g. the plain-text character `a' might be replaced by cipher text character 'q', 'b' might be replaced by 'x', 'c' by 'k' and so on). Each plain-text character should be replaced by a different cipher-text character. As part of your solution you must write and use at least the following functions/methods: (i) createCipher() which determines and returns the mapping from plain text to cipher text. Each plain text character ('a' .. 'z', ' ') must be randomly assigned a cipher-text character;
推荐答案
如果您想对字母进行随机播放,可以使用 Collections.shuffle(..)
方法.像这样:
If you want to shuffle an alphabet you can use the Collections.shuffle(..)
metode. Somethink like this:
public static void main(String[] args) {
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
char[] randomAlphabet = new char[alphabet.length];
// Copy to a List
List<Character> list = new ArrayList<Character>();
for (char c : alphabet) {
list.add(c);
}
// shuffle it
Collections.shuffle(list);
// Copy it back to an array
for (int i = 0; i < list.size(); i++) {
randomAlphabet[i] = list.get(i);
}
System.out.print("Random alphabet: ");
for (int i = 0; i < randomAlphabet.length; i++) {
System.out.print(" " + randomAlphabet[i]);
}
}
在我运行它时会给出以下信息:
That gives this when I run it:
Random alphabet: j b w q o c r f z k g n p a u s i d m y h v e l x t
这篇关于如何在Java中创建随机生成的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!