扫描和操纵字符串基本方向

时间:2015-11-18 14:40:38

标签: java

我正在创建一个代表迷宫的有向图。迷宫中的一个机制是翻转节点的方向。我只是从文件中读取节点,我想改变节点的方向,所以它是相反的。方向我的意思是N,W,S等。但是,当我使用扫描仪中的字符串时,我的函数不起作用,并在执行系统时返回null。但是在放入一个组成的字符串时会起作用,例如String test =“E”然后test = flipDirection(test)。这将测试设置为“W”。所以我知道flipDirection函数和String比较是有效的。第一行的输出为“E”,然后为null。

public Digraph(){

    FileReader reader = null;
    Scanner scan = null;


    try {
        reader = new FileReader("input.txt");
        scan = new Scanner(reader);
        scan.nextLine();

        while(scan.hasNextLine()){

            //read in unflipped nodes
            int row = scan.nextInt();
            int col = scan.nextInt();
            char color = scan.next().charAt(0);
            String circle = scan.next();
            String direction = scan.nextLine();


            //add a node to the graph
            Vertex v1 = new Vertex(row, col, color, circle, direction);
            addNode(v1);

            //add a flipped node
            System.out.println(direction);
            direction = flipDirection(direction);
            System.out.println(direction);
            Vertex v2 = new Vertex(row, col, color, circle, direction);
            addNode(v2);


        }


    } catch (FileNotFoundException e) {
        System.out.println(e.getLocalizedMessage());
    }

}


public static String flipDirection(String d){

    String flip = null;


    if(d.equals("N"))
        flip = "S";
    if(d.equals("S"))
        flip = "N";
    if(d.equals("E"))
        flip = "W";
    if(d.equals("W"))
        flip = "E";
    if(d.equals("NW"))
        flip = "SE";
    if(d.equals("SE"))
        flip = "NW";
    if(d.equals("NE"))
        flip = "SW";
    if(d.equals("SW"))
        flip = "NE";
    return flip;
}

public class Vertex {   
//name of vertex and a pointer to the first node in its adj linked list 
public int row;
public int col;
public char color;
public String direction;
public String isCircle; 

public Vertex(int row, int col, char color, String isCircle, String direction) {
    super();
    this.row = row;
    this.col = col;
    this.color = color;
    this.isCircle = isCircle;
    this.direction = direction;
}

@Override
public String toString() {
    return "Vertex [row=" + row + ", col=" + col + ", color=" + color
            + ", direction=" + direction + ", isCircle=" + isCircle + "]";
}

这就是输入文件的样子,没有额外的空格。方向是每行中文本的最后一部分

7 7

1 1 R N E

1 2 B N W

1 3 B N NW

1 4 R N NW

1 5 R N S

1 个答案:

答案 0 :(得分:1)

运行此代码后,我意识到读取nextLine()的{​​{1}}调用包含前导空格。添加direction来修复它:

trim()