0

还记得你在玩游戏时索引你名字的每个单词并将它们加在一起形成一个秘密数字吗?就像aay1+1+25=27

我试图用java中的各种方法做同样的事情,但我失败了。让我先分享我的脚本,然后告诉我我尝试了什么。

class test{
    public static void main(String args[]){
        int c = 3;
            String s = "c";
        ///now this is what all i tried:

        int value1 = (int)(s);
        ///i tried a cast, but that failed.

        String d = "4";
        int value2 = Integer.parseInt(d);
        ///when i try this, it correctly converts the string to an integer.

        Integer.parseInt(s);
        ///but when i try the above, it fails to do the same.
    }
}

在这段代码中,我尝试了 2 种不同的方法,这两种方法都以我想要但不准确的方式工作。

问题是它无法重新组织 c 是一个具有整数值的变量。

那么,有什么捷径可以做到吗?此外,现在字符串只有 1 位长,一旦用户输入他或她的姓名,我将使用 for 循环将所有字母完全循环。

如果没有任何捷径,我唯一的选择是做一个 if 语句,如:

if(letter=a;){
    value=1;
} 

或类似的东西?

感谢您的帮助!

4

2 回答 2

4

您不能将 String 直接转换为整数,您需要一次取一个字符并减去 char 的值,'a'然后加 1 :

public static void main(String[] a) {
    String s = "test";
    for (char c : s.toLowerCase().toCharArray()){
        System.out.println(charToInt(c));
    }
}
private static int charToInt(char c){
    return c - 'a' + 1;
}
于 2012-08-15T07:15:29.910 回答
1

在 Java 中,与大多数其他 C-eqsue 语言一样,char是 Number 类型。

char: char 数据类型是单个 16 位 Unicode 字符。它的最小值为“\u0000”(或 0),最大值为“\uffff”(或 65,535,包括在内)。

只是字母字符

所以你需要做的就是将每个字符转换成它的等价字符,char然后你就有了它的 ASCII/Unicode 值;我不会在这里讨论 Unicode,因为 ASCII 会通过 Unicode 映射到正确的位置。

// this will give you a Zero based int of the 
// UPPPERCASE alphabet which starts at `65` and
// ends at `90`. 
// See where the lowercases starts and ends?

char c = "My Name".charAt(0) - 65; 
// c = 'M' in this case which is 77 - 65 = 12

ASCII 码很容易翻译。

ASCII 表
(来源:asciitable.com

对于UPPERCASE字母来说,这只是一个循环chara 的所有 sString并获取它们的代码并减去65以获得0基值的练习。排除其他字符和过程也变得有点复杂lowercase,但你从表格中得到了这个想法。

可打印字符

请注意, “可打印”字符开始32并贯穿126这通常是您所做的,是减去32而不是65将所有“可打印”字符转换为零基数。

例子

以下将打印出所有“可打印”字符。

public class Main
{
    public static void main(final String[] args)
    {
        for (char i = 32; i <= 126; i++)
        {
            System.out.println(new Character(i));
        }
    }
}

解决方案

这是一个完整的解决方案,它将创建一个密码,所有可能的 *“可打印”字符。

public class Main
{
    public static void main(final String[] args)
    {
        int hash = 0;
        final String s = args[0];
        for (int c = 0; c < s.length(); c++)
        {
            hash = hash + s.charAt(c) - 32;
        }
        System.out.printf("Secret code for %s is %d", s, hash);
    }
}

我的名字的结果是

Secret code for Jarrod is 418
于 2012-08-15T07:15:10.320 回答