为什么字符的开关/外壳不起作用?

时间:2013-12-06 03:30:15

标签: java switch-statement character case

忽略第1-55行,有人可以告诉我为什么我的开关不适用于字符'v'和'| '无论什么时候出现?我放了一些打印行声明(第57,58行)来查看发生了什么,但它们甚至没有被执行!

只有第56行执行,然后继续读取文件以获取更多字符,跳过“v”和“|”的过程'人物......

每个其他开关都可以正常工作,不包括那两个。

input是一个BufferedReader,用于看起来像这样的文本文件

的test.txt

50
5
3
0
s-o o-o-o
| v v | v
o-o-o-oho
v |   v |
o-o-o-e-o

以下是代码的相关部分:

// loop through remaining lines of file
while (line != null) {
    // get characters in the line
    for (int j = 0; j < line.length(); j++) {

        // if character is even, it is a node
        ch = line.charAt(j);
        if (j % 2 == 0) {
            System.out.println("character even and is: " + ch);
            switch (ch) {
            case 's':
                System.out.println("s test worked");
                break;
            case 'e':
                System.out.println("e test worked");
                break;
            case 'o': // increase the node count
                break;
            }
        }

        // else character is odd, it is an edge
        else {
            System.out.println("character odd and is: " + ch);
            System.out.println(ch == 'v'); // Line 57
            System.out.println(ch == '|'); // Line 58
            switch (ch) {
            // horizontal wall
            case 'h':
                System.out.println("h test worked");
                break;
            // horizontal hall
            case '-':
                System.out.println("- test worked");
                break;
            // vertical wall
            case 'v':
                System.out.println("v test worked");
                break;
            // vertical hall
            case '|':
                System.out.println("| test worked");
                break;
            // unbreakable wall
            case ' ': // don't do anything
                break;
            }
        }
    }
    line = input.readLine();
}

此处is a link to complete, compilable code, given that you give the program the text file as an argument

1 个答案:

答案 0 :(得分:2)

这是因为您的代码假定所有边都位于奇数位置。但是,这仅对水平边缘是正确的;垂直边缘(即奇数行上的边缘)位于偶数位置。

您可以通过添加行计数器来解决此问题,如下所示:

int lineCounter = 0;
while (line != null) {
    // get characters in the line
    for (int j = 0; j < line.length(); j++) {
        // if character is even, it is a node
        ch = line.charAt(j);
        if ((lineCounter+j) % 2 == 0) {
            ...
        } else {
            ...
        }
    }
    line = input.readLine();
    lineCounter++;
}

此代码查找偶数行上奇数位置的边,以及奇数行上的偶数位置。

相关问题