有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么字符开关/案例不起作用?

忽略第1-55行,有人能告诉我为什么我的开关在字符“v”和“|”出现时不起作用吗?我放了一些打印行语句(第57行、第58行)来查看发生了什么,但它们甚至没有被执行

只执行第56行,然后继续读取文件中的更多字符,跳过处理“v”和“|”字符的过程

除这两个开关外,其他开关都可以正常工作

input是文本文件的BufferedReader,如下所示

测试。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) 个答案

  1. # 1 楼答案

    这是因为代码假定所有边都位于奇数位置。然而,这仅适用于水平边缘;垂直边缘(即奇数线上的边缘)位于偶数位置

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

    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++;
    }
    

    该代码在偶数行的奇数位置查找边,在奇数行的偶数位置查找边