text adventure/interactive fiction in java - java

I decided to create an account in order to ask a question I cant seem to figure out myself, or by some googling, hopefully I didn't just overlook it.
Essentially I am trying to make a text adventure game in Java, and am having a little trouble seeing how I should relate everything in the idea of objects. I have been successful in using XML stax and sending a file to the program, and using attributes and what not, to make it where the user can enter an integer associated with an option, and see if option requires an "item" or gives them an Item. I however did not take an OOP to this.
I want my new program to people able to take a string of user input in, instead of only an integer, and checking it against an array list if it exists. This is closer to the classic MUDs most may be familiar with.
I want to design it in a modular way, so I can slowly add on ideas, and more complexity to go along, so I don't want a "well it works so lets leave it alone" approach either.
Currently I simply want something close to this:
A Room object, which would have: an ID, Description, and interact-able
a Choice object (this one im not sure on) I thought about making an object to hold each rooms possible choices, both for exit, and for interact-ables
if so, the room object may need a Choice Object.
I've thought it over, tried some code, thought it over again, and every time, I keep ending up hard coding more than I feel I should, and making tons more variables than I feel are necessary, which makes me feel like i'm missing something crucial in my thinking.
I also want these rooms to be created through an inputted file, not generated in the code (so essentially the code is a story reader/crafter for any type, not one)
I have also been attempting this too long, and my solutions are becoming worse, but below was my most recent attempt at a rough Idea:
a GameManager class that takes the userInput and checks it some, before passing it along. I havent passed any data because im not sure of the approach. also im not used to regex, so some of that may also be wrong, if it is, maybe point it out, but that is not my focus
import java.util.Scanner;
public class GameManager {
private static final String EXIT_PHRASE = "exit";
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String userStringVal = "";
while(!userStringVal.equals(EXIT_PHRASE)){
userStringVal= userInput.nextLine();
if(checkKeywords(userStringVal)){
System.out.println("matches keyword");
}
else System.out.println("didnt match a keyword");
}
userInput.close();
}
public static boolean checkKeywords(String string){
boolean isKeyword = false;
string.toLowerCase();
if(string.matches("travel.*") || string.matches("search.*")){
System.out.println("passed first check");
String substring = string.substring(6);
if(matchDirection(substring)){
isKeyword = true;
}
}
return isKeyword;
}
public static boolean matchDirection(String string){
boolean hasDirection = false;
if(string.matches(".*\\bnorth|south|east|west|northeast|northwest|southeast| southwest|up|down")){
hasDirection = true;
}
return hasDirection;
}
}
The Room object I thought about as such:
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class Room {
private String roomDescription = "";
private int roomID=0;
private int northExit=0;
private int southExit=0;
private int eastExit=0;
private int westExit=0;
private int northeastExit=0;
private int northwestExit=0;
private int southeastExit=0;
private int southwestExit=0;
private int upExit=0;
private int downExit=0;
private String[] interactables = new String[10];
private Options options = new Options();
public Room(XMLStreamReader reader) throws XMLStreamException{
setAttValues(reader);
setRoomDescription(reader);
setUpOptions();
}
public void setinteractables(XMLStreamReader reader){
int count = reader.getAttributeCount();
for(int i = 0; i < count; i++){
interactables[i] = reader.getAttributeValue(i);
}
}
public void setAttValues(XMLStreamReader reader){
int count = reader.getAttributeCount();
for(int i = 0; i < count; i++){
String att = reader.getAttributeLocalName(i);
if(att !=""){
switch(att){
case "North": northExit=Integer.parseInt(att);
case "South": southExit=Integer.parseInt(att);
case "East": eastExit=Integer.parseInt(att);
case "West": westExit=Integer.parseInt(att);
case "NorthEast": northeastExit=Integer.parseInt(att);
case "NorthWest": northwestExit=Integer.parseInt(att);
case "SouthEast": southeastExit=Integer.parseInt(att);
case "SouthWest": southwestExit=Integer.parseInt(att);
case "Up": upExit=Integer.parseInt(att);
case "Down": downExit=Integer.parseInt(att);
case "ID": roomID=Integer.parseInt(att);
}
}
}
}
public void setRoomDescription(XMLStreamReader reader) throws XMLStreamException{
roomDescription = reader.getElementText();
}
public void setUpOptions(){
options.setCardinalPointers(northExit, southExit, eastExit, westExit);
options.setIntercardinalPointers(northeastExit, northwestExit, southeastExit, southwestExit);
options.setElevationPointers(upExit, downExit);
}
}
what can I do to make sure I dont have to state so many directions with so many variables?
here is a quick and rough idea of an Option class that I thought about, but i didn't finish deciding I am already too far in the wrong direction
public class Options {
private int northPointer = 0;
private int southPointer= 0;
private int eastPointer = 0;
private int westPointer = 0;
private int northeastPointer= 0;
private int northwestPointer = 0;
private int southeastPointer = 0;
private int southwestPointer = 0;
private int upPointer = 0;
private int downPointer = 0;
private String northInteractable = "";
private String southInteractable = "";
private String eastInteractable = "";
private String westInteractable = "";
private String northeastInteractable ="";
private String northwestInteractable = "";
private String southeastInteractable = "";
private String southwestInteractable = "";
private String upInteractable = "";
private String downInteractable = "";
public Options(){
}
public void setCardinalPointers(int north, int south, int east, int west){
northPointer = north;
southPointer = south;
eastPointer = east;
westPointer = west;
}
public void setIntercardinalPointers(int northeast, int northwest, int southeast, int southwest){
northeastPointer = northeast;
northwestPointer=northwest;
southeastPointer=southeast;
southwestPointer=southwest;
}
public void setElevationPointers(int up, int down){
upPointer = up;
downPointer = down;
}
public String whatToReturn(String string){
String importantPart = "";
if(string.matches("travel.*")){
String substring = string.substring(6);
}
else {
importantPart = "Interactable";
String substring = string.substring(6);
if (substring.matches("\\bnorth\\b")) {
if(northInteractable!=0){
}
}
else if (substring.matches("\\bsouth\\b"))
else if (substring.matches("\\beast\\b"))
else if (substring.matches("\\bwest\\b"))
else if (substring.contains("northeast"))
else if (substring.contains("northwest"))
else if (substring.contains("southeast"))
else if (substring.contains("southwest"))
else if (substring.contains("up"))
else if (substring.contains("down"))
}
return importantPart;
}
}
I did not see the adventure tag until after I typed this, so I will start perusing through there, but will still post this, so my apologies if there is a good answer to this and I have yet to find it.
as a recap: what would be a good way to relate a few objects to create a room object (that gets its information from a file (XML being what im used to)) having exits, descriptions, and interactions. and the user interacting with these based off keywords that can be inputted freely, and not restricted to say, index values of array's holding keywords.
Im thinking when the user types something like "travel north" to first check if they typed a keyword, in this case being travel, then a direction. Then somewhree else checking if it states travel, check north with a possible northExit a room may or may not have. Then if its another keyword, say like check, to make it easy also have the exact same directions, but check for a different string.
Then if room "northExit" exists, get an option somehow, with a pointer to another roomID. though This thought process causes me issues when thinking about future possibility of requiring items for getting to the next room. Also where to store/acquire these options is causing some difficulties.

There are two things I would like to introduce to you. The first, in the enum. You can think of this as a special kind of class where all the possible options are enumerated in the class definition. This is perfect for things like, in your case, directions. Enums can be simple, where you just list all of the possible options for use in other classes:
public enum Direction {
NORTH, NORTH_EAST, EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST, NOTH_WEST;
}
They can be a bit more complex, if you want them to have methods and attributes of their own:
public enum Direction {
NORTH(true), NORTH_EAST(false), EAST(true), SOUTH_EAST(false), SOUTH(true), SOUTH_WEST(false), WEST(true), NOTH_WEST(false);
private final boolean isCardinal;
private Direction(boolean isCardinal){
this.isCardinal = isCardinal;
}
public boolean isCardinal(){
return isCardinal;
}
public static Collection<Direction> getCardinalDirections(){
return Arrays.asList(Direction.values()).stream().filter(Direction::isCardinal).collect(Collectors.toList());
}
public static Collection<Direction> getIncardinalDirections(){
return Arrays.asList(Direction.values()).stream().filter(x -> !x.isCardinal()).collect(Collectors.toList());
}
}
Please read more about Java enum types here.
The second thing I would like to introduce to you is the data structure known as the Map. Maps are also known as Dictionaries, and that can often help understanding how they work. A Map will take one object and map it to another object, like how a Dictionary maps a word to its definition, or a phonebook maps a person's name to their phone number. We can simplify your Room class a ton by using a Map. I am not going to reproduce all of your code, since I'm focusing on your Room exists right now:
public class Room {
private Map<Direction, Room> exits;
public Room(){
this.exits = new HashMap<>();
}
public void setExit(Direction direction, Room room){
this.exits.put(direction, room);
}
public Room getExit(Direction direction){
return this.exits.get(direction);
}
}
Please read more about the Java Map interface here.
You will, of course, need to adapt your methods which are reading from XML, etc. But, now, your Room class should be greatly simplified.
I hope this points you in a helpful direction.

Related

Why do I get an error when trying to enter a parameter?

I'm not sure why, but I'm having a problem launching the code that I put together. For some reason, the code shows fatal errors when I enter a parameter within the methods. I have checked it several times but could not figure out what I did wrong.
Any advice would be appreciated.
public class songcode
{
/**
* #param args the command line arguments
*/
public class Songwriter{
private int song;
//variable for the amount of songs played
private int royalty;
//variable for the amount of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public int Adding_song(){
song = song + 1;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int Requesting_check(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
public static void main(String[] args){
}
}
}
See the comments for some quick help :)
public class SongWriter {
private int song;
//variable for the number of songs played
private int royalty;
//variable for the number of payments
private int identification_number;
//id number of the song writer
public String first_name;
//string for the first name of songwriter
public String last_name;
//string for the last name of the songwriter
public SongWriter(int myFavSong){
//define default values for vars above
this.song = myFavSong;
//'This' references the Songwriter object not required but useful practice.
}
// Lower case first word upcase second : camelCase
public int addingSong(int numSongs){
song = song + numSongs;
if(song > 100){
System.out.println("You are a big star!");
}
return(song);
}
public int requestingCheck(){
royalty = royalty + 10;
System.out.println("You just got payed");
return royalty;
}
// The main method shouldn't be nested another class
public static void main(String[] args){
//In java because our variables and functions are not static
//you need a reference to your SongWrite object
SongWriter songWriter = new SongWriter();
// Notice I modified your function to take in an int as a param
songWriter.song = addingSong(5);
System.out.println(songWriter.song);
}
}
because of lack information it is a little hard for us to solve your problem. Please provide us exacly what steps did you take and what errors did you get.
From what i see now, since your are using inner class (class inside of another class), you should make it static:
static class Songwriter{/*your code here*/ }
When you got that you can create an object of that class in your main() by calling your outer class, so in your case it would be:
songcode.Songwriter name = new songcode.Songwriter();
Now you can use your methods that are within your inner class by using name.method() like:
name.Requesting_check();
for(int i = 0; i<200; i++){
name.Adding_song();
}
Personally i would create a new java file called Songwriter.java, add a constructor and work with that, but maybe that's not what you were testing here ;-)
Hope it did help you and please next time provide more detailed informations, so we can give you an exact answer without guessing what's wrong and what exacly do you want to achieve with your code.

Card - Deck - Hand Java Project

I know everyone gets skeptical whenever people put homework on here but I've run out of options and could really use some direction. I have a project where I have to create a deck of cards and allow the user to pick the size of the hand and then fill that hand with random cards and display that to the user. I've found plenty of answers using ArrayLists but mine requires an array and I've tried everything I know and my code is either completely wrong or throws a bunch of errors.
So here are the problems I have:
1) The addCard method in the Hand class can be used to add one Card object at a time to the hand array until it is full. It should increment the cardsInHand counter each time a Card object is added to the Hand as long as there is room for the Card to fit into the Hand.
Here is the code for the Hand class:
public class Hand
{
private int handSize; //Holds the size of the hand
private int cardsInHand; //Holds the number of cards allowed in the hand
private Card[] hand; //Array of card objects
public Hand()
{
this.handSize = 5;
this.cardsInHand = 0;
this.hand = new Card[52];
}//end Default Constructor
public Hand(int handSize)
{
this.handSize = handSize;
}//end Parameterized Constructor
public Hand(Hand handIn)
{
this.handSize = handIn.handSize;
this.cardsInHand = handIn.cardsInHand;
this.hand = handIn.hand;
}//end Copy Constructor
public void addCard(Card card)
{
hand[card]; //--> throws a type mismatch exception (change card param to an int)
}//end addCard()
public int getHandSize()
{
return handSize;
}
public void setHandSize(int handSize)
{
this.handSize = handSize;
}
public int getCardsInHand()
{
return cardsInHand;
}
public void setCardsInHand(int cardsInHand)
{
this.cardsInHand = cardsInHand;
}
public Card[] getHand()
{
return hand;
}
public void setHand(Card[] hand)
{
this.hand = hand;
}
public String toString()
{
String msg = "";
return msg;
}//end toString()
}//end class
My addCard method is just all janky and I could really use some help trying to fill it so my program works. Any help or even a pointing in the right direction would be appreciated!
My addCard method is just all janky and I could really use some help trying to fill it so my program works. Any help or even a pointing in the right direction would be appreciated
Sometimes the best thing to do is stop, turn the screen off, get a pen and piece of paper and just nut it out without any code. Try to understand the problem and get the logic straight in your head.
Basically, you have a series of buckets into which you can put a Card. Before you can put a Card in a bucket, you need to know if you have any free buckets available.
If there are, you need to add the Card to the next available bucket (which should be pointed to by cardsInHand) and increment cardsInHand
Your error is because you're trying reference a "bucket" using a Card, but you can only reference a "bucket" by an index (number) so...
hand[card];
should be more like...
hand[cardsInHand] = card;
but only after you've determined if there is a free "bucket" available, and you should increment cardsInHand AFTER this statement
I'd also be worried about your constructors
public Hand(int handSize)
{
this.handSize = handSize;
}//end Parameterized Constructor
isn't initialising hand, so that's going to be null. A better solution might be to use existing constructors where possible to build a common "initialisation" path
public Hand() {
this(5);
}//end Default Constructor
public Hand(int handSize) {
this.handSize = handSize;
this.cardsInHand = cardsInHand;
this.hand = new Card[handSize];
}//end Parameterized Constructor
Also
public Hand(Hand handIn)
{
this.handSize = handIn.handSize;
this.cardsInHand = handIn.cardsInHand;
this.hand = handIn.hand;
}//end Copy Constructor
is worrying, as it's possible for some external class to make a change to handIn's hand and that change will be reflected by this instance as well (as they are pointing to the same array).
A "copy" constructor should be making a "copy" of the data. Realistically, this should probably be a "deep" copy, so any changes to Card don't mess with the Hand as well, but I'll start with a simple "shallow" copy to get you started
public Hand(Hand handIn) {
this.handSize = handIn.handSize;
this.cardsInHand = 0;
this.hand = new Card[this.handSize];
// Yes, I know there is a better way to do this, but
// I want the OP to learn something
for (int index = 0; index < handIn.hand.length; index++) {
Card card = handIn.hand[index];
if (card != null) {
hand[cardsInHand] = card;
cardsInHand++;
}
}
}//end Copy Constructor
#MadProgrammer already give better answer, I only want to chime a little. Knowing the OP project assignment using Java I want to comment a little about the Hand class design.
The task clearly said that user can pick hand with custom size, then the user will add card into the hand until the hand is full. Thus, I would propose the Hand class design like below.
public class Hand {
private int size; // Hold the amount of card can be hold by hand.
private int counter; // Count how many card added.
private Card[] cards; // The card on hand.
public Hand(int size) {
this.counter = 0;
this.size = size;
this.cards = new Card[size];
}
public void addCard(Card card) {
if (this.counter > this.size) {
throw new IllegalStateArgument("The hand is full of card!");
}
this.cards[this.counter] = card;
this.counter++;
}
public String show() {
StringBuilder result = new StringBuilder("The card on hand is: \n");
for (int i=0; i<this.size; i++) {
result.append(this.cards[i].toString()).append("\n");
}
return result.toString();
}
}
In my opinion the Hand class more easy to understand and achieve the goals of the Hand purpose from the task. However, just use this as reference and write code that you understand well.

how can I improve my code for this task

I am newbie to object orientated programming and trying to construct something which resembles a basic vote counter which should take an int parameter that represents a choice of two candidates and print the election results to the terminal window. albeit (the votes attributable to each candidate and the total votes cast)
The method I am looking for should also return a string that gives information on the success or failure of casting the vote.”your vote has been cast” “invalid choice, no vote cast"
I have created a class and the constructors and also implemented some basic get methods.
I am wondering how I should go about achieving this objective albeit through a conditional statement or using some sort of advanced method.
any help in terms of the syntax or wider approach would be appreciated.
public class VoteCounter {
private String candidate1;
private String candidate2;
private int candidate1Votes;
private int candidate2Votes;
private boolean completed;
public VoteCounter(String candidate1, String candidate2) {
this.candidate1 = candidate1;
this.candidate2 = candidate2;
this.candidate1Votes = 0;
this.candidate2Votes = 0;
this.completed = false;
}
public VoteCounter() {
this("CANDIDATE 1", "CANDIDATE 2");
}
public String getCandidate1 () {
return this.candidate1;
}
public String getCandidate2 () {
return this.candidate2;
}
public Boolean getCompleted () {
return this.completed;
}
public void setCompleted (boolean completed) {
this.completed = completed;
}
}
Something like this?
private String vote(int choice)
{
if(choice == 1)
{
candidate1Votes++;
}
else if(choice == 2)
{
candidate2Votes++;
}
else
{
return "invalid choice, no vote cast";
}
return "your vote has been cast";
}
I would do that in more general manner, avoiding code duplication and allowing to change number of candidates easily.
So let's make a class Vote similar to your VoteCounter but only for one candidate, with following fields:
private String candidate; // init this in constructor
private int candidateVotes; // initially 0, so no need to init
and with vote() method like in other answer but also without a candiadate, so:
public void vote() {
candidateVotes++;
}
Then you can make class VoteCounter which will take any number of candidates and will keep them in Array or Map.
Map<Integer, Vote> votes = new HashMap<>();
then you're creating vote method with choice:
public void vote(int choice) {
votes.get(choice).vote();
}
Then all is left is to iterate through your votes map and find the one with biggest number of votes.

Java enum alternative to how I did this?

Teaching myself Java by coding a MIDI handling program. One thing the program needs to be able to do is convert back and forth between MIDI note numbers and their corresponding compact string representations. I looked at using an enum setup, but due to naming constraints you can't do something like
c-1, c#-1, ... g9;
because of the sharps and negatives (yes, I'm following the convention that makes you end up with a negative octave :P).
It seemed clunky to have to make a conversion between what's allowed and what I want.
CNEG1("c-1"),
CSNEG1("c#-1"),
DNEG1("d-1"),
...
G9("g9");
So I came up with the static imports scheme below, and it works fine. However, I want to learn more about how to use enums, and I have a hunch that they might actually be somehow better suited to the task - if only I understood the ins and outs better. So that's my question: can anyone come up with an elegant way to provide the same functionality using an enum scheme? Moreover, would there be a strong argument for doing so?
public abstract class MethodsAndConstants {
public static final String TONICS[] = {"c","c#","d","d#","e","f","f#","g","g#","a","a#","b"};
static final NoteMap notemap = new NoteMap();
static class NoteMap{
static String map[] = new String[128];
NoteMap() {
for (int i = 0; i < 128; i++){
int octave = i/12 - 1;
String tonic = MethodsAndConstants.TONICS[i%12];
map[i] = tonic + octave;
}
}
}
public static int convert_midi_note(String name){
return indexOf(NoteMap.map, name);
}
public static String convert_midi_note(int note_num){
return NoteMap.map[note_num];
}
public static int indexOf(String[] a, String item){
return java.util.Arrays.asList(a).indexOf(item);
}
}
EDIT ------------------------------------------
After heavy consideration I think in this particular situation enums might be overkill after all. I might end up just using this code down here, same sort of static import approach but no longer even requiring anything like the NoteMap business up above.
note_num -> name conversions are really straightforward, and the name -> note_num stuff is just good ol' string-parsing fun.
public abstract class MethodsAndConstants {
public static final String[] TONICS = {"c","c#","d","d#","e","f","f#","g","g#","a","a#","b"};
static String convert(int i) {
String tonic = MethodsAndConstants.TONICS[i%12];
int octave = (i / 12) - 1;
return tonic + octave;
}
static int convert(String s) {
int tonic = java.util.Arrays.asList(MethodsAndConstants.TONICS).indexOf(s.substring(0,1));
if (s.contains("#")) tonic += 1;
int octave = Integer.parseInt(s.substring(s.length()-1));
if (s.contains("-")) octave -= 2; // case octave = -1
int note_num = ((octave + 1) * 12) + tonic;
return note_num;
}
}
You could use an enum to represent the pitch, but I might try encapsulating a Pitch in a class
public class Pitch {
private final int octave;
private final Note note;
public enum Note {
C("C",4), CSHARP("C#/Db",5), DFLAT("C#/Db",5), //and so on
private final String thePitch;
private final int midiAdjust;
private Note(final String thePitch, final int midiAdjust) {
this.thePitch = thePitch;
this.midiAdjust = midiAdjust;
}
String getThePitch() {
return thePitch;
}
int getMidiAdjust() {
return midiAdjust;
}
}
public Pitch(Note note, int octave) {
this.note = note;
this.octave = octave;
}
public int getMidiNumber(){
return 12*octave + note.getMidiAdjust();
}
}
This would account for the fact that the note (C, C#, D, D#, E...) is going to be one of a repeating set, but you could have all kinds of octaves, in this case handled by an int. It would greatly reduce the size of your enum.
EDIT: I added a few lines in here as an idea. You could pass a second parameter into the constructor of the enum to allow you to return a MIDI number representing the pitch. In this one I assumed that the lowest number represented by MIDI is an A, but I may be wrong on that. Also the 12*octave is intended to add a whole octave of pitches for each increment. You will probably have to adjust this slightly, as I see you are using that one weird notation.
Something like that:
public enum Note {
CNEG1("c-1"), CSNEG1("c#-1"), DNEG1("d-1");
private final String tonicOctave;
private Note(final String tonicOctave) {
this.tonicOctave = tonicOctave;
}
public String getTonicOctave() {
return this.tonicOctave;
}
public static Note fromTonicOctave(final String val) {
for (final Note note: Note.values()) {
if (note.getTonicOctave().equals(val)) {
return note;
}
}
return null;
}
}
Note, you can have as many parameters as you need in your enum, so if you need to separate tonic and octave, you can.

How to label edges with probabilities in graph using Jung 2

I am fairly new to Java and Jung. I am writing a program where I need to add probabilities on edges of the event occurrence(means probability of the event that data will flow from first node to other). I am a little confuse that will Max-Flow do the trick for me or do I need to use some other option or there is no option to do it within Jung and in that case do I need to write it on my own? Any help in this regard will be appreciated.
regards,
waqas
Do you intend to set the edge weights to represent the probabilities of certain events? The Max-Flow algorithm will use the "capacities" you assign to each edge to find the path of maximum flow from the source vertex to the sink vertex. What exactly are you trying to do here?
I'm not very sure what your final aim is, so I'll try my best to help out.
You can first represent the probabilities by defining a custom Edge and Edge Factory classes. What I did was:
0. Imports:
import org.apache.commons.collections15.Factory;
1. Add in your custom classes. They custom edge class might be something like:
public static class MyEdge {
private int flow;
private int capacity;
private String name;
private int eIndex;
public MyEdge(String name, int eIndex) {
this.name = name;
this.eIndex = eIndex;
}
public int getCapacity() {
return this.capacity;
}
public void setCapacity(int edgeCapacity) {
this.capacity = edgeCapacity;
}
public int getFlow() {
return this.flow;
}
public void setFlow(int edgeFlow) {
this.flow = edgeFlow;
}
public String toString() {
return this.name;
}
}
The custom edge factory is what actually creates your edges each time you draw them on the canvas graphically, it might look like:
public static class MyEdgeFactory implements Factory {
private static int defaultFlow = 0;
private static int defaultCapacity = 0;
private int edgeCount;
private MyEdgeFactory() {
}
public MyEdge create() {
String name = "E" + edgeCount;
MyEdge e = new MyEdge(name, edgeCount);
edgeCount++;
e.setFlow(defaultFlow);
e.setCapacity(defaultCapacity);
return e;
}
}
2. Tell your visualization viewer how to display the edge labels; you'll need to add this in wherever you're creating your graph and VisualizationViewer object (vv):
vv.getRenderContext().setEdgeLabelTransformer(new Transformer() {
public String transform(MyEdge e) {
return (e.toString() + " " + e.getFlow() + "/" + e.getCapacity());
}
});
Now everytime you create an edge, it's label will be of the form "E0 0/0", "E1 0/0" and so on.
I'll be posting detailed tutorials and code on my blog soon so you could watch that space if you're going to be spending significant time on whatever project you're working on.
Look at the way you're calling setEdgeLabelTransformer, you need to pass it a new Transformer(), like I've done in my code snippet numbered 2.
When you pass a new ToStringLabeller(), you're telling the viewer to label using the toString() method of the edge object. You'll need to pass a custom Transformer instead, just correct your code to look like mine and you'll be fine.

Categories

Resources