创建迭代hashmap的switch-case

时间:2014-10-24 16:33:35

标签: java hashmap

我有一个以这种方式制作的HashMap:

HashMap<M, Integer> t;

M是这样的一个类:

public class M {
    int s;
    char c;
}

所以就像我有一张这样的桌子:

+-------+-------+---------------+
|   s   |   c   |   Integer     |
+-------+-------+---------------+
+-------+-------+---------------+
|   0   |   0   |       1       |
+-------+-------+---------------+
|   0   |   1   |       0       |
+-------+-------+---------------+
|   0   |   3   |       5       |
+-------+-------+---------------+
|   1   |   0   |       2       |
+-------+-------+---------------+
|   1   |   1   |       0       |
+-------+-------+---------------+
|   2   |   0   |       3       |
+-------+-------+---------------+
|   2   |   1   |       0       |
+-------+-------+---------------+
|   3   |   0   |       3       |
+-------+-------+---------------+
|   3   |   1   |       3       |
+-------+-------+---------------+

表中的值是随机的。

我想要的是创建一个以这种方式制作的字符串:

case 0:
    if(ch == '0')
        st = 1;
    if(ch == '1')
        st = 0; 
    if(ch == '3')
        st = 5;             
    else
        st = -1;
    break;
case 1:
    if(ch == '0')
        st = 2;
    if(ch == '1')
        st = 0; 
    else
        st = -1;
    break;
case 2:
    if(ch == '0')
        st = 3;
    if(ch == '1')
        st = 0; 
    else
        st = -1;
    break;
case 3:
    if(ch == '0')
        st = 3;
    if(ch == '1')
        st = 3; 
    else
        st = -1;
    break;

解释:

  • case的数量是它们之间不同的数量
  • 在任何case中都有一个if。条件取决于列c,正文取决于Integer

所以在实践中:

Case(列“s”),if(列“c”),body(列“Integer”)。

我编写的代码很漂亮:

String g  = new String("");

for(int i = 0; i < numberOfSt(); i++) {
    g = g + "\t\t\t\tcase " + i + ": \n";
    int j = 0;
    for(Map.Entry<Move, Integer> entry : t.entrySet()) {
        Move key = entry.getKey();
        Integer value = entry.getValue();
        if(key.s == j) {
            g = g + "\t\t\t\t\tif(ch == '" + key.c + "')\n";
            g = g + "\t\t\t\t\t\tstate = " + value + ";\n";
        }
        j++;
    }
    g = g + "\t\t\t\t\telse\n";
    g = g + "\t\t\t\t\t\tstate = -1;\n";
    g = g + "\t\t\t\t\tbreak;\n";
}

问题在于它创建了错误的代码:

case 0: 
    if(ch == '0')
        st = 1;
    if(ch == '1')
        st = 0;
    if(ch == '3')
        st = 0;
    else
        st = -1;
    break;
case 1: 
    if(ch == '0')
        st = 1;
    if(ch == '1')
        st = 0;
    else
        st = -1;
    break;
case 2: 
    if(ch == '0')
        st = 1;
    if(ch == '1')
        st = 0;
    else
        st = -1;
    break;
case 3: 
    if(ch == '0')
        st = 1;
    if(ch == '1')
        st = 0;
    else
        st = -1;
    break;

“st =”错了..

任何人都可以帮助我吗? 感谢。

(我希望自己解释一下,否则我会添加你问我的细节..)

0 个答案:

没有答案