Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I need help troubleshooting my code its not working as it should. PLEASE FIX WHAT I HAVE NOT REWRITE THE ENTIRE PROGRAM PLEASE!! Depth First

I need help troubleshooting my code its not working as it should. PLEASE FIX WHAT I HAVE NOT REWRITE THE ENTIRE PROGRAM PLEASE!!

Depth First Search instructions:

Start with your Java program "prog340", ideally it should be working for Deliverable A.

Perform Depth First Search (DFS) on the graph, starting from the node with value "S". When you have the choice of two or more unexplored nodes to visit next, choose the nearest one. Break ties alphabetically by name. If your depth first search terminates without visiting every node in the graph, start again from the first node in the graph in alphabetical order by name that hasn't been visited.

After the DFS is completed, print the following:

The discovery and finish times of each node in the graph.

The classification of each edge in the graph. (Tree, Forward, Back, or Cross.)

Code:

Prog340.Java

import javax.swing.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*;

/** Driver class for deliverables. DO NOT MODIFY THIS CLASS!!!! ** ** @author ** Mike Stein * edited by Jessica Maistrovich **/

public class Prog340 extends JPanel /*implements ActionListener*/ { private static final long serialVersionUID = 1L; // Keep Eclipse happy. File inputFile; File outputFile; PrintWriter output; JFileChooser fileChooser; Graph g; JMenuBar menuBar; JMenu mainMenu, runMenu; JMenuItem readFile, exit; JMenuItem delivA, delivB, delivC, delivD, delivE;

public static void main(String[] args) throws FileNotFoundException { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } /** Create and show the GUI. ** For thread safety, this method should be invoked from the event-dispatching thread. **/ private static void createAndShowGUI() { // Create and set up the window JFrame frame = new JFrame("Prog340"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create and set up the content pane. JComponent newContentPane = new Prog340(); newContentPane.setOpaque(true);; // content panes must be opaque frame.setContentPane(newContentPane);; // Display the window. frame.pack(); frame.setVisible(true); } /** The constructor creates a new ProgramA object, and sets up the input and output files. **/ public Prog340() { super( new BorderLayout() );

try { // I like the colorful FileChooser. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); System.out.println( "Look for the pop up. Read a test file and then run a deliverable."); } catch (Exception e) { // exit on exception. System.err.format("Exception: %s%n", e); System.exit(0); }

fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Choose a file"); // Start looking for files at the current directory, not home. fileChooser.setCurrentDirectory(new File(".")); inputFile = null; // Create the menus menuBar = new JMenuBar(); mainMenu = new JMenu("Main Menu"); menuBar.add(mainMenu); readFile = new JMenuItem("Read File"); mainMenu.add(readFile); runMenu = new JMenu("Run Code"); mainMenu.add(runMenu); exit = new JMenuItem("Exit"); mainMenu.add(exit); delivA = new JMenuItem("Run Deliv A"); runMenu.add(delivA); delivB = new JMenuItem("Run Deliv B"); runMenu.add(delivB); delivC = new JMenuItem("Run Deliv C"); runMenu.add(delivC); delivD = new JMenuItem("Run Deliv D"); runMenu.add(delivD); delivE = new JMenuItem("Run Deliv E"); runMenu.add(delivE); // Here are the Action Listeners for the Menu Items readFile.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { g = new Graph(); readGraphInfo(g); } }); exit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { System.out.println("Goodbye"); System.exit(0);; } }); delivA.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { new DelivA( inputFile, g); } }); delivB.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { new DelivB( inputFile, g); } }); delivC.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { new DelivC( inputFile, g); } });

delivD.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { new DelivD( inputFile, g); } }); delivE.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { new DelivE( inputFile, g); } }); this.add(menuBar); }

/** Read the file containing the Strings, line by line, then process each line as it is read. **/ public void readGraphInfo( Graph g ) {

try { if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {

// Instantiate the selected input and output files. inputFile = fileChooser.getSelectedFile(); System.out.println( " Chosen file = " + inputFile + " "); } // read text file Scanner sc = new Scanner( inputFile ); // First line special: It contains "~", and "val", and the nodes with the edges. String firstLine = sc.nextLine(); String[] splitString = firstLine.split( " +" ); // Ignore first two fields of first line, Every other field is a node. for ( int i = 2; i < splitString.length; i++ ) { Node n = new Node( splitString[i] ); g.addNode( n ); } // Every other line gives the name and value of the Node, and any edges. int nodeIndex = 0; ArrayList nodeList = g.getNodeList(); while ( sc.hasNextLine() ) { String nextLine = sc.nextLine(); splitString = nextLine.split(" +");

Node n = nodeList.get( nodeIndex ); n.setName( splitString[0] ); n.setValue( splitString[1] );

for ( int i = 2; i < splitString.length; i++ ) { if ( !splitString[i].equals("~") ) { Node head = nodeList.get(i-2); int dist = Integer.parseInt( splitString[i] ); Edge e = new Edge( n, head, dist ); g.addEdge( e ); n.addOutgoingEdge( e ); head.addIncomingEdge( e ); } } nodeIndex++;

} sc.close();

} catch (Exception x) { System.err.format("ExceptionOuter: %s%n", x); } }

}

Node.java

import java.util.*;

// A node of a graph for the Spring 2018 ICS 340 program

public class Node {

private String name;

private String value; // The value of the Node which was stored in the value column

private String abbrev; // The abbreviation for the Node

private ArrayList outgoingEdges;

private ArrayList incomingEdges;

int discoveryTime, finishTime;

String color;

Node parent;

public Node(String abbreviation) {

abbrev = abbreviation;

value = null;

name = null;

outgoingEdges = new ArrayList();

incomingEdges = new ArrayList();

}

public String getAbbrev() {

return abbrev;

}

public String getName() {

return name;

}

public String getValue() {

return value;

}

public ArrayList getOutgoingEdges() {

return outgoingEdges;

}

public ArrayList getIncomingEdges() {

return incomingEdges;

}

public void setAbbrev(String abbreviation) {

abbrev = abbreviation;

}

public void setName(String name) {

this.name = name;

}

public void setValue(String value) {

this.value = value;

}

public void addOutgoingEdge(Edge e) {

outgoingEdges.add(e);

}

public void addIncomingEdge(Edge e) {

incomingEdges.add(e);

}

public void setColor(String color) {

this.color = color;

}

public String getColor() {

return color;

}

public void setPreviousNode (Node n) {

this.parent = n;

}

public Node getPreviousNode () {

return parent;

}

//print function

public String printOut() {

String output = "";

output += "Node " + this.getAbbrev() + " has outdegree " + this.getOutgoingEdges().size() + ".";

return output;

}

//print function

public String printIn() {

String output = "";

output += "Node " + this.getAbbrev() + " has indegree " + this.getIncomingEdges().size() + ".";

return output;

}

}

Edge.java

//import java.util.*;

// Edge between two nodes

public class Edge {

private int distance;

private Node tail;

private Node head;

public Edge(Node tailNode, Node headNode, int dist) {

distance = dist;

tail = tailNode;

head = headNode;

}

public Node getTail() {

return tail;

}

public Node getHead() {

return head;

}

public int getDistance() {

return distance;

}

public void setTail(Node newTail) {

tail = newTail;

}

public void setHead(Node newHead) {

head = newHead;

}

public void setDistance(int dist) {

distance = dist;

}

}

Graph.java

import java.util.*;

public class Graph {

ArrayList nodeList;

ArrayList edgeList;

public Graph() {

nodeList = new ArrayList();

edgeList = new ArrayList();

}

public ArrayList getNodeList() {

return nodeList;

}

public ArrayList getEdgeList() {

return edgeList;

}

public void addNode(Node n) {

nodeList.add(n);

}

public void addEdge(Edge e) {

edgeList.add(e);

}

// to start DFS a specific node using its value("s")

public Node startNode() {

for (Node start : nodeList) {

if (start.getValue().equalsIgnoreCase("s"))return start;

} // end of for loop

return null;

}

}

DelivB

Needs to be implemented correctly, here's what I have so far

import java.io.*; import java.util.Collections;

public class DelivB {

private File inputFile; private File outputFile; private PrintWriter output; private Graph g; static int time = 0;

//Constructor - DO NOT MODIFY public DelivB(File in, Graph gr) { inputFile = in; g = gr;

// Set up for writing to a file try { // Use input file name to create output file in the same location String inputFileName = inputFile.toString(); String outputFileName = inputFileName.substring(0, inputFileName.length() - 4).concat("_out.txt"); outputFile = new File(outputFileName);

// A Printwriter is an object that can write to a file output = new PrintWriter(outputFile); } catch (Exception x) { System.err.format("Exception: %s%n", x); System.exit(0); } // Calls the method that will do the work of deliverable B //runDelivB();

output.flush();

//********************************************************************************* // This is where your work starts // DFS Method from Pseudocode public static void DFS(Graph g) {

// Initialized: set every-node into white for (Node node1 : g.getNodeList()) { node1.setColor("WHITE"); node1.setPreviousNode(null); } // end of first loop time = 0; // this is where we decided which node we gonna vist. DFSvisit(g, g.startNode());

// we only do DFS_visit if node is undiscovered // sort Nodes by name before you discover in Compare ns = new Compare(); Collections.sort(g.getNodeList(), ns); for (Node node2 : g.getNodeList()) { if (node2.getColor().equalsIgnoreCase("WHITE")) { DFSvisit(g, node2); } } }

//DFS_VISIT Method from Pseudocode public static void DFSvisit(Graph gr, Node n) { time = time + 1; n.discoveryTime = time; // "int discoveryTime" instance variable created in Node class n.color = "GRAY"; // setting the parent nodes for (Edge v: n.getOutgoingEdges()) { if (v.getHead().color == "WHITE") { v.getHead().parent = n; DFSvisit(gr, v.getHead()); } } n.color = "BLACK"; time = time + 1; n.finishTime = time; // "int finishTime" instance variable created in Node class

//code for determining The classification of each edge in the graph. (Tree, Forward, Back, or Cross.) // B: back edge; C: cross edge; F: forward edge; T: tree edge System.out.printf(" %-15s\t%-15s ", "Edge", "Type"); for (Edge edge: g.edgeList) { Node u = edge.getTail(); Node v = edge.getHead(); String type; String edges = String.format("%s - %s" , u.getAbbrev(), v.getAbbrev()); if ((u.discoveryTime >= v.discoveryTime) && (u.finishTime <= v.finishTime)) type = "B"; else if ((u.discoveryTime < v.discoveryTime) && (u.finishTime > v.finishTime)) { if (v.parent == u) type = "T"; else type = "F"; } // else if ((v.discoveryTime < v.finishTime) && (v.finishTime < u.discoveryTime) && (u.discoveryTime < u.finishTime)) else type = "C"; System.out.printf("%-15s\t%-15s ", edges, type); } output.close(); }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

To troubleshoot and correctly implement the Depth First Search DFS on your graph I will focus on the DelivB class and the DFS methods Based on the pro... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Income Tax Fundamentals 2013

Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill

31st Edition

1111972516, 978-1285586618, 1285586611, 978-1285613109, 978-1111972516

More Books

Students also viewed these Programming questions

Question

According to the large loss principle you should?

Answered: 1 week ago