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"); // Process each problem in the file while (scanner.hasNextInt()) { int n = scanner.nextInt(); // Read the number of vertices/cities int[][] dist = new int[n][n]; // Distance matrix int[][] next = new int[n][n]; // Next matrix to reconstruct paths // Initialize matrices for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i][j] = scanner.nextInt(); if(dist[i][j] != 0) { next[i][j] = j; } } } // Floyd’s Algorithm 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(); }}
When I'm giving ./floyd graphfile.txt this command in the terminal it is only showing an output.txt file but there is nothing in the output.txt file
- Assistant
- User
The program should be able to read 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 0Problem2 Amatrix: n = 6 0 1 2 1 3 4
1 0 3 2 2 3
2 3 0 3 3 6
1 2 3 0 3 5
3 2 3 3 0 5
4 3 6 5 5 0 this input from the graphfile.txt and give the output as Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6
0 0 5 0 0 4 0
0 5 0 0 0 0 5
6 0 0 0 3 0 6
3 0 0 3 0 3 0
0 4 0 0 3 0 0 6 0 5 6 0 0 0 - Assistant
- User
- Assistant
The error you're encountering is due to the incorrect use of escape sequences in Java strings. In Java, the backslash
\is an escape character, and\sis not recognized as a valid escape sequence for a space character. The confusion may arise because\sis a valid regular expression for a whitespace character in many contexts outside of Java string literals.For splitting a string by whitespaces using the
splitmethod in Java, you have two main options:- Double backslashes
\\s+: Use double backslashes to correctly escape the backslash itself within a Java string, as the first backslash escapes the second, allowing\sto be correctly interpreted as a regular expression for a whitespace character.
- Double backslashes