Сохранить содержимое из метода void в переменную

Я пытаюсь распечатать и записать содержимое из метода void в файл, но, похоже, не могу заставить его работать. Я вызываю свой метод в main, и он отлично выводится на консоль. Я пробовал много разных подходов, но ни один из них не сработал. Может ли кто-нибудь помочь / направить меня в правильном направлении?

Я вставил свой код ниже для справки. В моей основной функции я вызываю 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();
        }

    }

}

Передайте поток, в который вы хотите записать вывод, через параметры метода

MadProgrammer 24.10.2018 22:15
dijkstra, в свою очередь, вызывает printArr (на самом деле это print). Вместо использования System.out вы можете передать другой PrintStream на dijkstra и, в свою очередь, на printArr.
Elliott Frisch 24.10.2018 22:17

Я передал поток печати методу Дейкстры public static void dijkstra(int graph[][], int src, PrintStream output) и изменил System.out to output.print(printArr(dist, N), но это дало мне ошибку. Любые идеи?

Wissam Hammoud 24.10.2018 22:54
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
0
3
936
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

   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);
   }
Ответ принят как подходящий

"Простым" решением было бы передать 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, так как результат зависит от успеха ввода;). Также см. Заявление try-with-resources для более подробной информации.

Это означает, что вы можете сделать что-то вроде ...

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

и он снова выведет вывод на консоль :)

Другие вопросы по теме