Search code examples
javafilemethodsio

save contents from void method to variable


I am trying to print write the contents from void method to a file but I cant seem to get it to work. I call my method in the main and it prints to the console just fine. I have tried many different approaches but not one worked. Can anyone help/guide me in the right direction?

I have pasted my code below for reference. In my main function I call dijkstra(M, SV - 1) that prints my array to the screen, my goal is to have that same array printed to a file.

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Scanner;

public class Main_2 {
    static int SV = 0; // source vertex
    static int N = 0;
    static int M[][];
    public static int distance[];

    static int minDistance(int dist[], Boolean shortestPath[]) {
        int min = Integer.MAX_VALUE, minI = -1;
        for (int i = 0; i < N; i++)
            if (shortestPath[i] == false && dist[i] <= min) {
                min = dist[i];
                minI = i;
            }
        return minI;
    }

    public static void printArr(int dist[], int n) {
//      System.out.println("vertex        distance");
        for (int i = 0; i < N; i++)
            System.out.println("[" + dist[i] + "]");
    }

    public static void dijkstra(int graph[][], int src) {
        // The output array. dist[i] will hold
        // the shortest distance from src to i
        int dist[] = new int[N];
        // sptSet[i] will true if vertex i is included in shortest
        // path tree or shortest distance from src to i is finalized
        Boolean shortestPath[] = new Boolean[N];

        // Initialize all distances as INFINITE and stpSet[] as false
        for (int i = 0; i < N; i++) {
            dist[i] = Integer.MAX_VALUE;
            shortestPath[i] = false;
        }

        // Distance of source vertex from itself is always 0
        dist[src] = 0;

        // Find shortest path for all vertices
        for (int i = 0; i < N - 1; i++) {
            // Pick the minimum distance vertex from the set of vertices
            // not yet processed. u is always equal to src in first
            // iteration.
            int u = minDistance(dist, shortestPath);

            // Mark the picked vertex as processed
            shortestPath[u] = true;

            // Update dist value of the adjacent vertices of the
            // picked vertex.
            for (int j = 0; j < N; j++)

                // Update dist[v] only if is not in sptSet, there is an
                // edge from u to v, and total weight of path from src to
                // v through u is smaller than current value of dist[v]
                if (!shortestPath[j] && graph[u][j] != 0 && dist[u] != Integer.MAX_VALUE
                        && dist[u] + graph[u][j] < dist[j])
                    dist[j] = dist[u] + graph[u][j];
        }

        // print the constructed distance array
        printArr(dist, N);


    }

    public static void main(String[] args) {
        try {
            int i = 0, j = 0; // counters
            FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt"); // name of input file must go in here
            Scanner scan = new Scanner(textFile);
            N = scan.nextInt(); // read in the size
            String flush = scan.nextLine(); // gets rid of linefeed
            System.out.println(N);
            M = new int[N][N]; // instantiates array
            // this loop reads in matrix from input file
            String line;
            while (i < N && (line = scan.nextLine()) != null) {
                j = 0;
                String delim = " ";
                String tokens[] = line.split(delim);
                for (String a : tokens) {
                    M[i][j] = Integer.parseInt(a);
                    j++;
                }
                i++;
            }
            if (i > N)
                ;
            SV = scan.nextInt();
        } catch (Exception e) {
            e.printStackTrace();
        }

        printMatrix(M);
        System.out.println(SV);
        System.out.println();
        dijkstra(M, SV - 1);

        try {
            FileWriter fw = new FileWriter("Shortest_path.txt"); // writes transitive closure to file
            BufferedWriter bw = new BufferedWriter(fw);
            for (int i = 0; i < N; i++) {
//              bw.write(dist[i]);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void printMatrix(int[][] Matrix) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                System.out.print(Matrix[i][j]);
                System.out.print(" ");

            }
            System.out.println();
        }

    }

}

Solution

  • "A" simple solution, would be to pass the PrintStream you want to use to the method, for example...

    public static void printArr(int dist[], int n, PrintStream ps) {
        for (int i = 0; i < N; i++) {
            ps.println("[" + dist[i] + "]");
        }
    }
    

    This will then require you to pass a PrintStream instance to the method when ever you call it. Since dijkstra also calls printArr, you will need to pass the instance of the PrintStream to it as well...

    public static void dijkstra(int graph[][], int src, PrintStream ps) {
        //...
    
        // print the constructed distance array
        printArr(dist, N, ps);
    
    }
    

    Then you just create an instance of the PrintStream you want to use and pass it to the methods...

    public static void main(String[] args) {
        try (FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt")) {
            int i = 0, j = 0; // counters
            Scanner scan = new Scanner(textFile);
            N = scan.nextInt(); // read in the size
            String flush = scan.nextLine(); // gets rid of linefeed
            System.out.println(N);
            M = new int[N][N]; // instantiates array
            // this loop reads in matrix from input file
            String line;
            while (i < N && (line = scan.nextLine()) != null) {
                j = 0;
                String delim = " ";
                String tokens[] = line.split(delim);
                for (String a : tokens) {
                    M[i][j] = Integer.parseInt(a);
                    j++;
                }
                i++;
            }
            if (i > N)
                ;
            SV = scan.nextInt();
    
            try (PrintStream ps = new PrintStream("EXAMPLE(2).txt")) {
                printMatrix(M);
                System.out.println(SV);
                System.out.println();
                dijkstra(M, SV - 1, ps);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    

    I restructured your main method slightly, as the output is depended on the success of the input ;). Also see The try-with-resources statement for more details

    This means you could do something like...

    dijkstra(M, SV - 1, System.out);
    

    and it would once again print the output to the console :)