我想将一个句子37 37“”与3个结果分开,如37 37'',并将每个结果保存为3个变量。 这是我的代码
public class Graph<T extends Comparable <T>> {
private Vertex<T> head;
private int size;
private boolean isDirected;
private boolean hasEdgeValue;
private T startState;
private List finishedState;
public Graph() { this(false, false); }
public Graph(boolean isDirected, boolean hasEdgeValue) {
head = null;
size = 0;
finishedState = new LinkedList<T>();
this.isDirected = isDirected;
this.hasEdgeValue = hasEdgeValue;
}
public void createGraph(Scanner inFile) {
T fromVert, toVert;
T weight; //weight
while(inFile.hasNext()) {
fromVert = (T) inFile.next();//save 37 here
toVert = (T) inFile.next();//save 37 here
if(hasEdgeValue) {
weight = (T) inFile.next(); //save ' '(white-space or a if inpute is "a" here
insertVertex(fromVert);
insertVertex(toVert);
insertEdge(fromVert, toVert, weight);
if(!isDirected) {
insertEdge(toVert, fromVert, weight);
}
}
else {
insertVertex(fromVert);
insertVertex(toVert);
insertEdge(fromVert, toVert, null);
if(!isDirected) {
insertEdge(toVert, fromVert, null);
}
}
}
}
}
这是我的输入数据
14 37“”
37 37“a”
37 37“b”
37 37“c”
37 37“d”
37 37“e”
我用useDelimeter但是它不起作用请帮助我 结果应为fromVert为37,toVert 37,如果输入为37 37,则权重为''
答案 0 :(得分:0)
while (inFile.hasNextLine()){
String data = inFile.hasNextLine();
if(!data.isEmpty()) {
int i = data.indexOf('"');
String sentance = data.substring(0,i);
String betweenQuote = data.substring(i+1, data.length()-1);
String[] verts = sentance.split(" ");
fromVert = verts[0];
toVert = verts[1];
weight = betweenQuote;
}
}
你可能不想使用Next()&lt; - 因为这会自动跳过空格。而是使用包含空格的NextLine()。然后可能会做一些字符串操作,这通常会解决你的问题。