import java.io.*; import java.util.Scanner; public class floyd { public static void…
- User
import java.io.*; import java.util.Scanner;
public class floyd {
public static void main(String[] args) throws FileNotFoundException { if(args.length != 1) { System.err.println("Usage: floyd <graph-file>"); return; } String inputFile = args[0]; Scanner scanner = new Scanner(new File(inputFile)); PrintWriter writer = new PrintWriter("output.txt"); // To skip non-integer lines such as "Problem1 Amatrix: n = 7" while(scanner.hasNextLine()) { String line = scanner.nextLine().trim(); // Try to extract ‘n’ from lines like "Problem1 Amatrix: n = 7" if(line.startsWith("Problem") && line.contains("n =")) { int n = Integer.parseInt(line.split("n =")[1].trim()); // Now we know ‘n’, we can proceed with the adjacency matrix int[][] dist = new int[n][n]; int[][] next = new int[n][n]; // Read the matrix for(int i = 0; i < n; i++) { if(scanner.hasNextLine()) { line = scanner.nextLine().trim(); String[] parts = line.split("\\s+"); for(int j = 0; j < n; j++) { dist[i][j] = Integer.parseInt(parts[j]); if(dist[i][j] != 0 && i != j) { next[i][j] = j; } } } } for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } } writer.println("Problem" + ": n = " + n); writer.println("Pmatrix:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { writer.print(next[i][j] + " "); } writer.println(); } // Reconstructing paths for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { int u = i; String path = "V" + (i+1); while(u != j){ u = next[u][j]; path += " V" + (u+1); } writer.println("V" + (i+1) + "-V" + (j+1) + ": shortest path and length"); writer.println(path + ": " + dist[i][j]); } } } } scanner.close(); writer.close(); }} } The program is giving error as ./floyd graphfile.txt Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1154) at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1786) at java.base/java.util.Scanner.hasNextLine(Scanner.java:1615) at floyd.main(floyd.java:17) The input is Problem1 Amatrix: n = 7 0 6 5 4 6 3 6 6 0 6 4 5 5 3 5 6 0 3 1 4 6 4 4 3 0 4 1 4 6 5 1 4 0 5 5 3 5 4 1 5 0 3 6 3 6 4 5 3 0
- Assistant
- User
- Assistant