java—将单词“one”改为数字“1”,以此类推

ohfgkhjo  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(301)

**结束。**此问题不符合堆栈溢出准则。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

6年前关门了。
改进这个问题
我不是要你们在你们有想法之前完成我的工作,只是我接到了这个任务
完成函数int comp(字符串s1,字符串s2)。对于此功能,s1和s2是以下“一”、“二”、“三”、“四”之一。例如,s1可以是2,s2可以是4。很明显,s1和s2对应于数字。如果s1(作为一个数字)小于s2(作为一个数字),则函数comp应返回一个负数;如果它们相等(作为一个数字),则返回零;否则返回一个正数。例如,comp(“2”,“4”)应该返回一个负数,因为2小于4。
但是我不知道如果已经分配给s1“一”,我会如何分配s1和1。
有什么建议吗?
致以最诚挚的问候。

cygmwpex

cygmwpex1#

将字符串和数字放在一起有几种可能(枚举、对象、Map),但最好的解决方法是Map String , Integer .

public class test
{
    private HashMap<String, Integer> map = new HashMap<String, Integer>();

    public test(){
        map.put("one",1);
        map.put("two",2);
        map.put("three",3);
        map.put("four",4);
        //TODO: ....
    }

    public static void main(String args[]) {

        System.out.print(new test().comp("two","four"));

    }

    public int comp(String s1, String s2) {
        int i1 = map.get(s1);
        int i2 = map.get(s2);
        return (i1<i2 ? -1 : (i1==i2 ? 0 : 1));
    }
}
zengzsys

zengzsys2#

如果输入仅限于 "one","two","three","four" 你可以用 String.equals 以及 if-else 块来指定正确的int值。像这样:

private int parseInt(String s) {
    if(s.equals("one"))
        return 1;
    if(s.equals("two"))
        return 2;
...
}

更新一个有趣的实现可以通过 enum :

public class Main {

    public enum NUMBER {

        zero("zero", 0), one("one", 1), two("two", 2), three("three", 3), four("four", 4);

        private String  string;
        private int     number;

        NUMBER(String s, int n) {
            string = s;
            number = n;
        }

        public int getInt() {
            return number;
        }
    };

    static public void main(String[] args) {
        System.out.println(compare("one", "two"));
        System.out.println(compare("one", "one"));
        System.out.println(compare("zero", "two"));
        System.out.println(compare("four", "two"));
    }

    public static int compare(String s1, String s2) {
        int n1 = NUMBER.valueOf(s1).getInt();
        int n2 = NUMBER.valueOf(s2).getInt();
        return Integer.compare(n1, n2);
    }
}
qv7cva1a

qv7cva1a3#

我想你可以用一个比较数组:

String[] value = {"one", "two", "three", "four"}

public int comp(String s1, String s2) {
    int one = getVal(s1);
    int two = getVal(s2);
    // Compare how you like
    return Integer.compare(one, two);
}

public int getVal(String rel) {
    for (int i = 1; i < 5; i++) {
        // i - 1 due to array indexes starting at 0.
        if (value[i - 1].equalsIgnoreCase(rel)) {
            return i;
        }
    }
    return /* some error value for inability to parse */;
}

我特别喜欢这个,因为你不需要 Integer.parseInt() 如果数字不可读,则会引发运行时异常。你可以自己扔一个如果 getVal 函数找不到合适的数字。
如果你想使用任何数字,我会说,它可能是合理的,通过数字分解数字,并将它们连接为数字,而不是数字,但这可能是一个更先进的比目前的目标在这里:)

相关问题