我在netbeans中编写程序,但我无法在.txt文件中打印它。 indead,我的编程代码确实正常工作。 我认为问题出在最后一行代码中。 这是我的代码:
import java.io.*;
import java.util.*;
public class converttopathbased_bfs
{
static String START;
static String END;
static int numberOfNodes;
static int numberOfArcs;
static int numberOfCommodities;
static int OriginDestinationOfCommodities[][] = new int[numberOfCommodities][2];
static int neighborhoods[][] = new int[numberOfNodes][numberOfNodes];
static int variableCosts[][] = new int[numberOfNodes][numberOfNodes];
static int capacities[][] = new int[numberOfNodes][numberOfNodes];
static int fixedCosts[][] = new int[numberOfNodes][numberOfNodes];
static int demandOfCommodities[] = new int[numberOfCommodities];
java.io.File file = new java.io.File("pathBasedTest.txt");
java.io.PrintWriter output;
public static void main(String[] args) throws Exception
{
java.io.File data = new java.io.File("samples//test.txt");
Scanner scanner = new Scanner(data);
numberOfNodes = scanner.nextInt();
numberOfArcs = scanner.nextInt();
numberOfCommodities = scanner.nextInt();
Graph graph = new Graph();
for (int i = 0; i < numberOfArcs; i++)
{
int m = scanner.nextInt() - 1;
int n = scanner.nextInt() - 1;
String S = "";
String E = "";
S = Integer.toString(m + 1);
E = Integer.toString(n + 1);
scanner.nextInt();
scanner.nextInt();
scanner.nextInt();
graph.addEdge(S, E);
scanner.nextInt();
scanner.nextInt();
}
for (int i = 0; i < numberOfCommodities; i++)
{
converttopathbased_bfs.START = scanner.next();
converttopathbased_bfs.END = scanner.next();
scanner.nextInt();
LinkedList<String> visited = new LinkedList();
visited.add(START);
new converttopathbased_bfs().breadthFirst(graph, visited);
}
}
private void breadthFirst(Graph graph, LinkedList<String> visited) throws Exception
{
output = new java.io.PrintWriter (file) ;
LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());
// examine adjacent nodes
for (String node : nodes)
{
if (visited.contains(node))
{
continue;
}
if (node.equals(END))
{
visited.add(node);
printPath(visited);
visited.removeLast();
break;
}
}
// in breadth-first, recursion needs to come after visiting adjacent nodes
for (String node : nodes)
{
if (visited.contains(node) || node.equals(END))
{
continue;
}
visited.addLast(node);
breadthFirst(graph, visited);
visited.removeLast();
}
}
private void printPath(LinkedList<String> visited)
{
for (String node : visited)
{
output.printf("s", node);
output.printf(" ");
}
output.printf("\n");
}
}
答案 0 :(得分:1)
主要问题是,每次调用output
时都会创建breadhtfirst
。您应该只在代码的开头创建一次,然后在代码的末尾关闭它。
你可能想要最后几行:
for (String node : visited)
{
output.printf("%s ", node);
}
output.println();
但我们需要更多信息才能确定。
您还需要在代码末尾关闭该文件。
output.close();
答案 1 :(得分:0)
尝试关闭文件流:
output.close()
答案 2 :(得分:0)
您需要添加以下两行:
output.flush();
output.close();
将其转换为BufferedWriter并使用append方法。