I’m attempting to calculate the critical path, using the critical path method. I have several test cases, and the output should be printed to a file called “tarea2.out”.
The problem is that when I print the file, it seems I overwrite the output for each case and finally output only shows me the last of them. I know it’s silly, but I’m new to Java and I can not make the output is correct
Here’s my code:
package tarea;
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
*
* @author Francisco
*/
public class Main {
public static int c;
public static void recorrido(int[][] adj) throws IOException{
int n=adj.length;
int casitas[][] = new int[n][2];
int mejorCamino[] = new int [n];
int temp;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
temp = adj[i][j];
if(temp > -1){
if(temp + casitas[i][0]>casitas[j][0]){
casitas[j][0] = temp + casitas[i][0];
mejorCamino[j] = i;
}
}
}
}
//Hacemos el paso hacia atrás.
for(int y=0;y<n;y++)
casitas[y][1] = casitas[n-1][0];
for (int j=n-1;j>=0;j--){
for(int i=0;i<n;i++){
temp = adj[i][j];
if(temp > -1){
casitas[i][1]= Math.min(casitas[j][1] - temp , casitas[i][1]);
}
}
}
int x=n-1;
String cam = "";
while(x>0){
if(x==n-1)
cam= mejorCamino[x] + " " + x;
else
cam= mejorCamino[x] + " " + x + "\n" + cam;
adj[mejorCamino[x]][x] = -1;
x = mejorCamino[x];
}
//Calculamos las holguras con nuestra nueva matriz
String mac="";
int HT , HL;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
temp = adj[i][j];
if (temp > -1){
HT = casitas[j][1] - temp - casitas[i][0];
HL = casitas[j][0] - temp - casitas[i][0];
mac += "\n" + i + " " + j + " " + HT + " " + HL;
if (HT>HL)
mac += " R";
}
}
}
String sFichero = "tarea2.out";
File fichero = new File(sFichero);
BufferedWriter bw = new BufferedWriter(new FileWriter(sFichero));
bw.write("Case " + c + ": total duration " + casitas[n-1][0] );
bw.write("\n");
bw.write(cam);
bw.write(mac);
bw.write("\n");
// Hay que cerrar el fichero
bw.close();
}
}
You’re creating the BufferedWriter every time you call
recorridomethod.The file will be rewritten every time. Add the
trueparameter to the constructor to tell that it will open the file in append modeAlso, it would be better if you open the file once in all the application and in
recorridojust write the content instead of open/close the file many times.