gpt4 book ai didi

java - 扫描和操作字符串基本方向

转载 作者:行者123 更新时间:2023-11-30 07:47:02 26 4
gpt4 key购买 nike

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

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

最佳答案

运行此代码后,我意识到读取 directionnextLine() 调用包含前导空格。添加 trim() 调用来修复它:

   String direction = scan.nextLine().trim();

关于java - 扫描和操作字符串基本方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33782923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com