Question

Hello, i need help with this homework:

ml ALT -i (Body) - 11 - A Ă Aa Ao IŲ - x x A-D-A- AaBbcc AaBbCcDc Normal 1 No Spac- Font 5 Paragraph CSIT 254 -- ProgrammingSubtitle Subtle Em... Emphasis Intense E... Strong Quote Intense Q... or Re Sel Styles Editi CSIT 254 - Programming Lab 9- Gr

Code provided:

public class DirectedWeightedExampleSlide18
{
public static void main(String[] args)
{
int currentVertex, userChoice;
Scanner input = new Scanner(System.in);

// create graph using your WeightedGraph based on author's Graph
WeightedGraph myGraph = new WeightedGraph(4);

// add labels
myGraph.setLabel(0,"Spot zero");
myGraph.setLabel(1,"Spot one");
myGraph.setLabel(2,"Spot two");
myGraph.setLabel(3,"Spot three");

// Add each edge (this directed Graph has 5 edges,
// so we add 5 edges)
myGraph.addEdge(0,2,9);

myGraph.addEdge(1,0,7);

myGraph.addEdge(2,3,12);

myGraph.addEdge(3,0,15);
myGraph.addEdge(3,1,6);

// let's pretend we are on v2
currentVertex = 2;
  
  
// do - this is a good place for the top of the loop

// display the current vertex

System.out.println("\nYou are currently at vertex " + currentVertex +
"-" + myGraph.getLabel(currentVertex));

// who are our neighbors?
System.out.println("neighbors of " + currentVertex + " are:\n");

System.out.printf("%3s %-10s %4s\n","#","Neighbor","Cost");
System.out.printf("%3s %-10s %4s\n","===","==========","====");

if (myGraph.neighbors(currentVertex).length == 0)
System.out.println("No Neighbors");
else
{
for (int neighbor : myGraph.neighbors(currentVertex))
{
System.out.printf("%3d %-10s %4d\n",
neighbor,
myGraph.getLabel(neighbor),
myGraph.getWeight(currentVertex,neighbor));
}
System.out.println();
}

// suppose I was interacting with user,
// I could ask for their choice

/* 1: if their choice is -1 then say goodbye
2: else if the user enters a value too large or too small report an out of range error
3: else if their choice is a valid neighbor then change the current vertex to that choice
4: else then report the vertex they entered is unreachable

hint for 3:
else if myGraph.isEdge(currentVertex,choice)
currentVertex=choice;
*/
  
// while...this is a good place for the bottom of the loop
  
System.out.println("\nyou need to modify this file: \n\tDirectedWeightedExampleSlide18.java"+
"\npress enter to continue...");
input.nextLine();
}
}

public class UndirectedNonWeightedExampleSlide17
{
public static void main(String[] args)
{
int currentVertex, userChoice;
Scanner input = new Scanner(System.in);

// create graph using Author's Graph
Graph myGraph = new Graph(4);

// add labels
myGraph.setLabel(0,"Spot zero");
myGraph.setLabel(1,"Spot one");
myGraph.setLabel(2,"Spot two");
myGraph.setLabel(3,"Spot three");

// Add each edge (this undirected Graph has 5 edges,
// so we add 10 edges)
myGraph.addEdge(0,1);
myGraph.addEdge(1,0);

myGraph.addEdge(0,2);
myGraph.addEdge(2,0);

myGraph.addEdge(0,3);
myGraph.addEdge(3,0);

myGraph.addEdge(1,3);
myGraph.addEdge(3,1);

myGraph.addEdge(2,3);
myGraph.addEdge(3,2);

// let's pretend we are on v2
currentVertex = 2;

  
do
{
// display the current vertex
System.out.println("\nYou are currently at node "
+ currentVertex + "-" + myGraph.getLabel(currentVertex));

// display our neighbors
System.out.println("neighbors of " + currentVertex + " are:");

for (int neighbor : myGraph.neighbors(currentVertex))
System.out.printf("%2d-%s\n",neighbor,myGraph.getLabel(neighbor));
System.out.println();

// suppose I was interacting with user, (hey, I am)
// I will ask for their choice
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();

// make sure not too small nor too big
while (userChoice < -1 || userChoice >= myGraph.size())
{
System.out.println("\n" + userChoice + " is not a valid value");
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();
}

// if their choice is -1 then exit
if (userChoice == -1)
System.out.println("Good bye!");
else
{
// if their choice is a valid neighbor
if (myGraph.isEdge(currentVertex,userChoice))
currentVertex=userChoice; // then move to new vertex....
else
// report the vertex they entered is unreachable
System.out.println("\nYou can't go to " + userChoice
+ "-" + myGraph.getLabel(userChoice)
+ " from " + currentVertex
+ "-" + myGraph.getLabel(currentVertex));
}
} while (userChoice != -1);
}
}

public class UndirectedNonWeightedExampleSlide19House
{
public static void main(String[] args)
{
int currentVertex, userChoice;
Scanner input = new Scanner(System.in);
final int KITCHEN = 0;
final int PANTRY = 1;
final int DINING_ROOM = 2;
final int BACK_FOYER = 3;
final int FRONT_FOYER = 4;
final int STUDY = 5;
final int LIVING_ROOM = 6;

// create graph using Author's Graph
Graph myGraph = new Graph(7);

// add labels
myGraph.setLabel(KITCHEN,"Kitchen");
myGraph.setLabel(PANTRY,"Pantry");
myGraph.setLabel(DINING_ROOM,"Dining Room");
myGraph.setLabel(BACK_FOYER,"Back Foyer");
myGraph.setLabel(FRONT_FOYER,"Front Foyer");
myGraph.setLabel(STUDY,"Study");
myGraph.setLabel(LIVING_ROOM,"Living Room");

// Add each edge (this undirected Graph has 7 edges,
// so we add 14 edges)
myGraph.addEdge(KITCHEN,PANTRY);
myGraph.addEdge(PANTRY,KITCHEN);

myGraph.addEdge(PANTRY,DINING_ROOM);
myGraph.addEdge(DINING_ROOM,PANTRY);

myGraph.addEdge(DINING_ROOM,FRONT_FOYER);
myGraph.addEdge(FRONT_FOYER,DINING_ROOM);

myGraph.addEdge(KITCHEN,BACK_FOYER);
myGraph.addEdge(BACK_FOYER,KITCHEN);

myGraph.addEdge(BACK_FOYER,FRONT_FOYER);
myGraph.addEdge(FRONT_FOYER,BACK_FOYER);

myGraph.addEdge(FRONT_FOYER,LIVING_ROOM);
myGraph.addEdge(LIVING_ROOM,FRONT_FOYER);

myGraph.addEdge(BACK_FOYER,STUDY);
myGraph.addEdge(STUDY,BACK_FOYER);

// let's pretend we are in FRONT_FOYER
currentVertex = FRONT_FOYER;

do
{
// display the current vertex
System.out.println("\nYou are currently in room "
+ currentVertex + "-" + myGraph.getLabel(currentVertex));

// display our neighbors
System.out.println("neighbors of " + currentVertex + " are:");

for (int neighbor : myGraph.neighbors(currentVertex))
System.out.printf("%2d-%s\n",neighbor,myGraph.getLabel(neighbor));
System.out.println();

// suppose I was interacting with user, (hey, I am)
// I will ask for their choice
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();

// make sure not too small nor too big
while (userChoice < -1 || userChoice >= myGraph.size())
{
System.out.println("\n" + userChoice + " is not a valid value");
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();
}

// if their choice is -1 then exit
if (userChoice == -1)
System.out.println("Good bye!");
else
{
// if their choice is a valid neighbor
if (myGraph.isEdge(currentVertex,userChoice))
currentVertex=userChoice; // then move to new vertex....
else
// report the vertex they entered is unreachable
System.out.println("\nYou can't go to " + userChoice
+ "-" + myGraph.getLabel(userChoice)
+ " from " + currentVertex
+ "-" + myGraph.getLabel(currentVertex));
}
} while (userChoice != -1);
}

public class Graph
{
private boolean[ ][ ] edges;
private Object[ ] labels;

/**
* Constructor
* @param n the number of nodes for the graph being created
*/
public Graph(int n)
{
edges = new boolean[n][n]; // All values initially false
labels = new Object[n]; // All values initially null
}

/**
* addEdge method receives 2 locations. The second location is added
* as a neighbor to the first Location passed.
* @param source Location to receive a neighbor
* @param target Location to be added as a neighbor
*/
public void addEdge(int source, int target)
{
edges[source][target] = true;
}

/**
* getLabel returns the label associated with the vertex passed
* @param vertex the vertex that we want the label for
* @return the label for the vertex
*/
public Object getLabel(int vertex)
{
return labels[vertex];
}

/**
* isEdge method receives 2 Locations. the second Location is checked
* to see if it is a neighbor of the first Location
* @param source Location to check for a neighbor
* @param target other Location that is being checked to see if it is a neighbor
* @return boolean that indicates if the second Location is a neighbor of the first Location
*/
public boolean isEdge(int source, int target)
{
return edges[source][target];
}

/**
* the neighbors method builds an array of Location which are the neighbors of
* the Location passed
* @param vertex the Location to get the neighbors from
* @return an array of int that contains the neighbors of vertex
*/
public int[ ] neighbors(int vertex)
{
int i;
int count;
int[ ] answer;

// First count how many edges have the vertex as their source
count = 0;
for (i = 0; i < labels.length; i++)
{
if (edges[vertex][i])
count++;
}

// Allocate the array for the answer
answer = new int[count];

// Fill the array for the answer
count = 0;
for (i = 0; i < labels.length; i++)
{
if (edges[vertex][i])
answer[count++] = i;
}

return answer;
}


/**
* removeEdge method receives 2 locations. The second location is removed
* as a neighbor to the first Location passed.
* @param source Location to lose a neighbor
* @param target Location to be removed as a neighbor
*/
public void removeEdge(int source, int target)
{
edges[source][target] = false;
}


/**
* setLabel assigns a label associated with the vertex passed
* @param vertex the vertex that we want to set the label for
* @param newLabel the label for the vertex
*/
public void setLabel(int vertex, Object newLabel)
{
labels[vertex] = newLabel;
}


/**
* size method returns the number of vertices in the graph
* @return number of vertices
*/
public int size( )
{
return labels.length;
}

}

public class ProgLab09GraphsSum18
{

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
String userChoice;
Scanner input = new Scanner(System.in);
  
do
{
System.out.println("\nThese use Graph.java (provided)");
System.out.println("A - UndirectedNonWeightedExampleSlide17.java");
System.out.println("B - UndirectedNonWeightedExampleSlide19House.java");
System.out.println("\nThis uses WeightedGraph.java (<--you need to modify)");
System.out.println("C - DirectedWeightedExampleSlide18.java (<--you need to modify)");
System.out.println("\nX - Exit");
System.out.print("\nEnter selection: ");
  
userChoice = input.nextLine();
switch (userChoice.toLowerCase())
{
case "a":
UndirectedNonWeightedExampleSlide17.main(args);
break;
case "b":
UndirectedNonWeightedExampleSlide19House.main(args);
break;
case "c":
DirectedWeightedExampleSlide18.main(args);
break;
case "x":
System.out.println("\nBye bye!");
break;
default:
System.out.println("\nhuh?");
  
}
} while (!(userChoice.equalsIgnoreCase("X")));  
}
}

public class WeightedGraph
{
public WeightedGraph(int n)
{
// stub
}

public void addEdge(int source, int target, int weight)
{
// stub
}
  
public Object getLabel(int vertex)
{
// stub
return null;
}
  
public boolean isEdge(int source, int target)
{
// stub
return false;
}
  
public int[ ] neighbors(int vertex)
{
// stub
int [ ] answer = { };
return answer;
}
  
public void removeEdge(int source, int target)
{
// stub
}
public void setLabel(int vertex, Object newLabel)
{
// stub
}
  
public int size( )
{
// stub
return 0;
}

public int getWeight(int source, int target)
{
// stub
return 0;
}
  
public void setWeight(int source, int target, int weight)
{
// stub
}
  
  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Working code implemented in Java and appropriate comments provided for better understanding:

Here I am attaching code for these files:

  • Graph.java
  • WeightedGraph.java
  • ProgLab09GraphsSum18.java
  • DirectedWeightedExampleSlide18.java
  • UndirectedNonWeightedExampleSlide17.java
  • UndirectedNonWeightedExampleSlide19House.java

Source code for Graph.java:

public class Graph
{
private boolean[ ][ ] edges;
private Object[ ] labels;

/**
* Constructor
* @param n the number of nodes for the graph being created
*/
public Graph(int n)
{
edges = new boolean[n][n]; // All values initially false
labels = new Object[n]; // All values initially null
}

/**
* addEdge method receives 2 locations. The second location is added
* as a neighbor to the first Location passed.
* @param source Location to receive a neighbor
* @param target Location to be added as a neighbor
*/
public void addEdge(int source, int target)
{
edges[source][target] = true;
}

/**
* getLabel returns the label associated with the vertex passed
* @param vertex the vertex that we want the label for
* @return the label for the vertex
*/
public Object getLabel(int vertex)
{
return labels[vertex];
}

/**
* isEdge method receives 2 Locations. the second Location is checked
* to see if it is a neighbor of the first Location
* @param source Location to check for a neighbor
* @param target other Location that is being checked to see if it is a neighbor
* @return boolean that indicates if the second Location is a neighbor of the first Location
*/
public boolean isEdge(int source, int target)
{
return edges[source][target];
}

/**
* the neighbors method builds an array of Location which are the neighbors of
* the Location passed
* @param vertex the Location to get the neighbors from
* @return an array of int that contains the neighbors of vertex
*/
public int[ ] neighbors(int vertex)
{
int i;
int count;
int[ ] answer;

// First count how many edges have the vertex as their source
count = 0;
for (i = 0; i < labels.length; i++)
{
if (edges[vertex][i])
count++;
}

// Allocate the array for the answer
answer = new int[count];

// Fill the array for the answer
count = 0;
for (i = 0; i < labels.length; i++)
{
if (edges[vertex][i])
answer[count++] = i;
}

return answer;
}


/**
* removeEdge method receives 2 locations. The second location is removed
* as a neighbor to the first Location passed.
* @param source Location to lose a neighbor
* @param target Location to be removed as a neighbor
*/
public void removeEdge(int source, int target)
{
edges[source][target] = false;
}


/**
* setLabel assigns a label associated with the vertex passed
* @param vertex the vertex that we want to set the label for
* @param newLabel the label for the vertex
*/
public void setLabel(int vertex, Object newLabel)
{
labels[vertex] = newLabel;
}


/**
* size method returns the number of vertices in the graph
* @return number of vertices
*/
public int size( )
{
return labels.length;
}

}

Source code for WeightedGraph.java:

public class WeightedGraph
{
private int edges[][];
private Object[] labels;
  
public WeightedGraph(int n)
{
edges = new int[n][n];
labels = new Object[n];
}

public void addEdge(int source, int target, int weight)
{
edges[source][target] = weight;
}
  
public Object getLabel(int vertex)
{
return labels[vertex];
}
  
public boolean isEdge(int source, int target)
{
if (edges[source][target] > 0)
return true;
else
return false;
}
  
public int[ ] neighbors(int vertex)
{
int i;
int count;
int [ ] answer = { };
  
count = 0;
for (i = 0; i < labels.length; i++)
{
if (edges[vertex][i] > 0)
count++;
}
  
answer = new int[count];
  
count = 0;
for (i = 0; i < labels.length; i++)
{
if (edges[vertex][i] > 0)
answer[count++] = i;
}
  
return answer;
}
  
public void removeEdge(int source, int target)
{
edges[source][target] = 0;
}
public void setLabel(int vertex, Object newLabel)
{
labels[vertex] = newLabel;
}
  
public int size( )
{
return labels.length;
}

public int getWeight(int source, int target)
{
return edges[source][target];
}
  
public void setWeight(int source, int target, int weight)
{
edges[source][target] = weight;
}
  
  
}

Source code for ProgLab09GraphsSum18.java:

import java.util.Scanner;

public class ProgLab09GraphsSum18
{

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
String userChoice;
Scanner input = new Scanner(System.in);
  
do
{
System.out.println("\nThese use Graph.java (provided)");
System.out.println("A - UndirectedNonWeightedExampleSlide17.java");
System.out.println("B - UndirectedNonWeightedExampleSlide19House.java");
System.out.println("\nThis uses WeightedGraph.java (<--you need to modify)");
System.out.println("C - DirectedWeightedExampleSlide18.java (<--you need to modify)");
System.out.println("\nX - Exit");
System.out.print("\nEnter selection: ");
  
userChoice = input.nextLine();
switch (userChoice.toLowerCase())
{
case "a":
UndirectedNonWeightedExampleSlide17.main(args);
break;
case "b":
UndirectedNonWeightedExampleSlide19House.main(args);
break;
case "c":
DirectedWeightedExampleSlide18.main(args);
break;
case "x":
System.out.println("\nBye bye!");
break;
default:
System.out.println("\nhuh?");
  
}
} while (!(userChoice.equalsIgnoreCase("X")));
  
  
}
  
}

Source code for DirectedWeightedExampleSlide18.java:

import java.util.Scanner;

public class DirectedWeightedExampleSlide18
{
public static void main(String[] args)
{
int currentVertex, userChoice, previous, totalCost;
Scanner input = new Scanner(System.in);

// create graph using your WeightedGraph based on author's Graph
WeightedGraph myGraph = new WeightedGraph(4);

// add labels
myGraph.setLabel(0,"Spot zero");
myGraph.setLabel(1,"Spot one");
myGraph.setLabel(2,"Spot two");
myGraph.setLabel(3,"Spot three");

// Add each edge (this directed Graph has 5 edges,
// so we add 5 edges)
myGraph.addEdge(0,2,9);

myGraph.addEdge(1,0,7);

myGraph.addEdge(2,3,12);

myGraph.addEdge(3,0,15);
myGraph.addEdge(3,1,6);

// let's pretend we are on v2
currentVertex = 2;
previous = 2;
totalCost = 0;
  
// do - this is a good place for the top of the loop
do
{
totalCost += myGraph.getWeight(previous, currentVertex);
System.out.println("\nso far you have accrued " + totalCost + " cost");
  
// display the current vertex

System.out.println("\nYou are currently at vertex " + currentVertex +
"-" + myGraph.getLabel(currentVertex));

// who are our neighbors?
System.out.println("neighbors of " + currentVertex + " are:\n");

System.out.printf("%3s %-10s %4s\n","#","Neighbor","Cost");
System.out.printf("%3s %-10s %4s\n","===","==========","====");

if (myGraph.neighbors(currentVertex).length == 0)
System.out.println("No Neighbors");
else
{
for (int neighbor : myGraph.neighbors(currentVertex))
{
System.out.printf("%3d %-10s %4d\n",
neighbor,
myGraph.getLabel(neighbor),
myGraph.getWeight(currentVertex,neighbor));
}
System.out.println();
}

// suppose I was interacting with user, (hey, I am)
// I will ask for their choice
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();

// make sure not too small nor too big
while (userChoice < -1 || userChoice >= myGraph.size())
{
System.out.println("\n" + userChoice + " is not a valid value");
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();
}

// if their choice is -1 then exit
if (userChoice == -1)
System.out.println("Good bye!");
else
{
// if their choice is a valid neighbor
if (myGraph.isEdge(currentVertex,userChoice))
{
previous = currentVertex;
currentVertex=userChoice; // then move to new vertex....
}
else
// report the vertex they entered is unreachable
System.out.println("\nYou can't go to " + userChoice
+ " from " + currentVertex);
}
} while (userChoice != -1);
}
}

Source code for UndirectedNonWeightedExampleSlide17.java:

import java.util.Scanner;

public class UndirectedNonWeightedExampleSlide17
{
public static void main(String[] args)
{
int currentVertex, userChoice;
Scanner input = new Scanner(System.in);

// create graph using Author's Graph
Graph myGraph = new Graph(4);

// add labels
myGraph.setLabel(0,"Spot zero");
myGraph.setLabel(1,"Spot one");
myGraph.setLabel(2,"Spot two");
myGraph.setLabel(3,"Spot three");

// Add each edge (this undirected Graph has 5 edges,
// so we add 10 edges)
myGraph.addEdge(0,1);
myGraph.addEdge(1,0);

myGraph.addEdge(0,2);
myGraph.addEdge(2,0);

myGraph.addEdge(0,3);
myGraph.addEdge(3,0);

myGraph.addEdge(1,3);
myGraph.addEdge(3,1);

myGraph.addEdge(2,3);
myGraph.addEdge(3,2);

// let's pretend we are on v2
currentVertex = 2;

  
do
{
// display the current vertex
System.out.println("\nYou are currently at node "
+ currentVertex + "-" + myGraph.getLabel(currentVertex));

// display our neighbors
System.out.println("neighbors of " + currentVertex + " are:");

for (int neighbor : myGraph.neighbors(currentVertex))
System.out.printf("%2d-%s\n",neighbor,myGraph.getLabel(neighbor));
System.out.println();

// suppose I was interacting with user, (hey, I am)
// I will ask for their choice
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();

// make sure not too small nor too big
while (userChoice < -1 || userChoice >= myGraph.size())
{
System.out.println("\n" + userChoice + " is not a valid value");
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();
}

// if their choice is -1 then exit
if (userChoice == -1)
System.out.println("Good bye!");
else
{
// if their choice is a valid neighbor
if (myGraph.isEdge(currentVertex,userChoice))
currentVertex=userChoice; // then move to new vertex....
else
// report the vertex they entered is unreachable
System.out.println("\nYou can't go to " + userChoice
+ "-" + myGraph.getLabel(userChoice)
+ " from " + currentVertex
+ "-" + myGraph.getLabel(currentVertex));
}
} while (userChoice != -1);
}
}

Source code for UndirectedNonWeightedExampleSlide19House.java:

import java.util.Scanner;

public class UndirectedNonWeightedExampleSlide19House
{
public static void main(String[] args)
{
int currentVertex, userChoice;
Scanner input = new Scanner(System.in);
final int KITCHEN = 0;
final int PANTRY = 1;
final int DINING_ROOM = 2;
final int BACK_FOYER = 3;
final int FRONT_FOYER = 4;
final int STUDY = 5;
final int LIVING_ROOM = 6;

// create graph using Author's Graph
Graph myGraph = new Graph(7);

// add labels
myGraph.setLabel(KITCHEN,"Kitchen");
myGraph.setLabel(PANTRY,"Pantry");
myGraph.setLabel(DINING_ROOM,"Dining Room");
myGraph.setLabel(BACK_FOYER,"Back Foyer");
myGraph.setLabel(FRONT_FOYER,"Front Foyer");
myGraph.setLabel(STUDY,"Study");
myGraph.setLabel(LIVING_ROOM,"Living Room");

// Add each edge (this undirected Graph has 7 edges,
// so we add 14 edges)
myGraph.addEdge(KITCHEN,PANTRY);
myGraph.addEdge(PANTRY,KITCHEN);

myGraph.addEdge(PANTRY,DINING_ROOM);
myGraph.addEdge(DINING_ROOM,PANTRY);

myGraph.addEdge(DINING_ROOM,FRONT_FOYER);
myGraph.addEdge(FRONT_FOYER,DINING_ROOM);

myGraph.addEdge(KITCHEN,BACK_FOYER);
myGraph.addEdge(BACK_FOYER,KITCHEN);

myGraph.addEdge(BACK_FOYER,FRONT_FOYER);
myGraph.addEdge(FRONT_FOYER,BACK_FOYER);

myGraph.addEdge(FRONT_FOYER,LIVING_ROOM);
myGraph.addEdge(LIVING_ROOM,FRONT_FOYER);

myGraph.addEdge(BACK_FOYER,STUDY);
myGraph.addEdge(STUDY,BACK_FOYER);

// let's pretend we are in FRONT_FOYER
currentVertex = FRONT_FOYER;

do
{
// display the current vertex
System.out.println("\nYou are currently in room "
+ currentVertex + "-" + myGraph.getLabel(currentVertex));

// display our neighbors
System.out.println("neighbors of " + currentVertex + " are:");

for (int neighbor : myGraph.neighbors(currentVertex))
System.out.printf("%2d-%s\n",neighbor,myGraph.getLabel(neighbor));
System.out.println();

// suppose I was interacting with user, (hey, I am)
// I will ask for their choice
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();

// make sure not too small nor too big
while (userChoice < -1 || userChoice >= myGraph.size())
{
System.out.println("\n" + userChoice + " is not a valid value");
System.out.print("\nWhere would you like to go? (-1 to exit): ");
userChoice = input.nextInt();
}

// if their choice is -1 then exit
if (userChoice == -1)
System.out.println("Good bye!");
else
{
// if their choice is a valid neighbor
if (myGraph.isEdge(currentVertex,userChoice))
currentVertex=userChoice; // then move to new vertex....
else
// report the vertex they entered is unreachable
System.out.println("\nYou can't go to " + userChoice
+ "-" + myGraph.getLabel(userChoice)
+ " from " + currentVertex
+ "-" + myGraph.getLabel(currentVertex));
}
} while (userChoice != -1);
}

}

Sample Output Screenshots:

Hope it helps, if you like the answer give it a thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
Hello, i need help with this homework: Code provided: public class DirectedWeightedExampleSlide18 { public static void...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with this project: Code provided: HOUSEGRAPH.java public class HouseGraph extends LinkedGraph { //...

    I need help with this project: Code provided: HOUSEGRAPH.java public class HouseGraph extends LinkedGraph { // establish rooms private final Location kitchen = new Location("Kitchen"); private final Location pantry = new Location("Pantry"); private final Location diningRoom = new Location("Dining Room"); private final Location backFoyer = new Location("Back Foyer"); private final Location frontFoyer = new Location("Front Foyer"); private final Location study = new Location("Study"); private final Location livingRoom = new Location("Living Room"); private final Location stairs = new Location("Stairs"); private final...

  • import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        //...

    import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.println("Welcome to the Triangle Maker! Enter the size of the triangle.");        Scanner keyboard = new Scanner(System.in);    int size = keyboard.nextInt();    for (int i = 1; i <= size; i++)    {    for (int j = 0; j < i; j++)    {    System.out.print("*");    }    System.out.println();    }    for (int...

  • I need the following java code commented import java.util.Scanner; public class Main { public static void...

    I need the following java code commented import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner (System.in); int productNo=0; double product1; double product2; double product3; double product4; double product5; int quantity; double totalsales=0; while(productNo !=0) System.out.println("Enter Product Number 1-5"); productNo=input.nextInt(); System.out.println("Enter Quantity Sold"); quantity=input.nextInt(); switch (productNo) { case 1: product1=1.00; totalsales+=(1.00*quantity); break; case 2: product2=2.00; totalsales+=(2.00*quantity); break; case 3: product3=6.00; totalsales+=(6.00*quantity); break; case 4: product4=23.00; totalsales+=(23.00*quantity); break; case 5: product5=17.00; totalsales+=(17.00*quantity); break;...

  • must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int...

    must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int [] arr); public static void quickSort(int [] arr); public static void mergeSort(int [] arr); The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: //merge method //merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely,...

  • Consider the java Graph class below which represents an undirected graph in an adjacency list. How...

    Consider the java Graph class below which represents an undirected graph in an adjacency list. How would you add a method to delete an edge from the graph? // Exercise 4.1.3 (Solution published at http://algs4.cs.princeton.edu/) package algs41; import stdlib.*; import algs13.Bag; /** * The <code>Graph</code> class represents an undirected graph of vertices * named 0 through V-1. * It supports the following operations: add an edge to the graph, * iterate over all of the neighbors adjacent to a vertex....

  • Convert into pseudo-code for below code =============================== class Main {    public static void main(String args[])...

    Convert into pseudo-code for below code =============================== class Main {    public static void main(String args[])    {        Scanner s=new Scanner(System.in);        ScoresCircularDoubleLL score=new ScoresCircularDoubleLL();        while(true)        {            System.out.println("1--->Enter a number\n-1--->exit");            System.out.print("Enter your choice:");            int choice=s.nextInt();            if(choice!=-1)            {                System.out.print("Enter the score:");                int number=s.nextInt();                GameEntry entry=new GameEntry(number);   ...

  • How would I traverse through this graph? Provide example code, please! class Edge {    int src,...

    How would I traverse through this graph? Provide example code, please! class Edge {    int src, dest;    Edge(int src, int dest)    {        this.src = src;        this.dest = dest;    } }; // class to represent a graph object class Graph {    // A list of lists to represent adjacency list    List<List<Integer>> adj = new ArrayList<>();    // Constructor to construct graph    public Graph(List<Edge> edges)    {        // allocate memory for adjacency list        for (int i = 0; i < edges.size(); i++) {            adj.add(i,...

  • (How do I remove the STATIC ArrayList from the public class Accounts, and move it to...

    (How do I remove the STATIC ArrayList from the public class Accounts, and move it to the MAIN?) import java.util.ArrayList; import java.util.Scanner; public class Accounts { static ArrayList<String> accounts = new ArrayList<>(); static Scanner scanner = new Scanner(System.in);    public static void main(String[] args) { Scanner scanner = new Scanner(System.in);    int option = 0; do { System.out.println("0->quit\n1->add\n2->overwirte\n3->remove\n4->display"); System.out.println("Enter your option"); option = scanner.nextInt(); if (option == 0) { break; } else if (option == 1) { add(); } else...

  • Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args)...

    Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn);    else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...

  • I cannot get this to work in IntelliJ import java.util.Scanner; public class Fibonacci { public static...

    I cannot get this to work in IntelliJ import java.util.Scanner; public class Fibonacci { public static int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); System.out.println(fibonacci(n)); in.close(); } }

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT