将内容从void方法保存到变量

时间:2018-10-24 20:12:16

标签: java file methods io

我正在尝试将内容从void方法写入文件,但似乎无法正常工作。我在主要调用我的方法,它可以很好地打印到控制台。我尝试了许多不同的方法,但没有一种有效。谁能在正确的方向帮助/指导我?

我在下面粘贴了我的代码以供参考。在我的主要函数中,我调用dijkstra(M,SV-1),将我的数组打印到屏幕上,我的目标是将相同的数组打印到文件中。

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();
        }

    }

}

2 个答案:

答案 0 :(得分:1)

   try (FileWriter fileWriter = new FileWriter("YourFileName.txt");
           PrintWriter printWriter = new PrintWriter(fileWriter)) {

       for (int i=0; i<N; i++) {
           printWriter.printf(Integer.toString(dist[i]));
       }
   } catch (Exception e) {
       System.out.println(e);
   }

答案 1 :(得分:0)

“一个”简单的解决方案是将您要使用的PrintStream传递给该方法,例如...

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

这将要求您在每次调用时将PrintStream实例传递给该方法。由于dijkstra也调用printArr,因此您也需要将PrintStream的实例传递给它...

public static void dijkstra(int graph[][], int src, PrintStream ps) {
    //...

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

}

然后,您只需创建要使用的PrintStream的实例,然后将其传递给方法...

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();
    }

}

由于输出取决于输入的成功;),我对您的main方法进行了稍微的重组。另请参阅The try-with-resources statement了解更多详情

这意味着您可以执行类似的操作...

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

,它将再次将输出打印到控制台:)