简体   繁体   English

如何在java中创建一个将输入转换为数字组合的系统

[英]How to create a system that turns an input into a combination of numbers in java

I'm trying to create a system that takes a key from the user.我正在尝试创建一个从用户那里获取密钥的系统。 eg 'ab'.例如'ab'。 Convert the letters into their position on the alphabet, (ab = 1, 2) and then add them together.将字母转换为它们在字母表中的位置,(ab = 1, 2),然后将它们相加。 So an example would look like.所以一个例子看起来像。

Input: abc输入: abc

Output: 6输出:6

This is what I've tried so far.这是我迄今为止尝试过的。

String alphabet = ("abcdefghijklmnopqrstuvwxyz");
        System.out.println("Please input a key");
        Scanner key = new Scanner(System.in);
        String keyInput = key.nextLine();



        for (int i = 0; i < keyInput.length(); i++) {
            char letter = keyInput.charAt(i);
            int[] alphLetter = new int[alphabet.indexOf(letter)];
            System.out.println(alphLetter[i]);

You can get a character's position in the alphabet by subtracting 'a' from it (and adding one, since you want it one-based).您可以通过从字符中减去'a'来获得字符在字母表中的位置(并加 1,因为您希望它基于 1)。 I think the easier approach would be to stream the characters of the string, convert them to their positions and sum them:我认为更简单的方法是流式传输字符串的字符,将它们转换为它们的位置并将它们相加:

int result = key.chars().map(c -> c - 'a' + 1).sum();

It's not clear if alphabet will always be in the standard order or if it could be shuffled?目前尚不清楚alphabet是否始终按标准顺序排列,或者是否可以改组?

If you're just dealing with the standard alphabet you can do something simple like this:如果您只是处理标准字母表,则可以执行以下简单操作:

int sum = 0;
for(int i=0; i<keyInput.length(); i++)
{
    sum += 1 + keyInput.charAt(i) - 'a';
}
System.out.println("Sum: " + sum);

If the alphabet could be shuffled you'll first need to build a map of character positions.如果alphabet可以洗牌,您首先需要构建一个字符位置图。 You can use a simple array for this.您可以为此使用一个简单的数组。

String alphabet = "mgpqrhivwxjklostufncbyzade";
int[] charPos = new int[alphabet.length()];
for(int i=0; i<alphabet.length(); i++) 
    charPos[alphabet.charAt(i)-'a'] =  i + 1;

int sum = 0;
for(int i=0; i<keyInput.length(); i++)
{
    sum += charPos[keyInput.charAt(i)-'a'];
}
System.out.println("Sum: " + sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM