Class help

Hi
I cant figure out what my problem is here.
I have created 2 classes here one that creates a circle
called ball
and one that has handlers to drag the circle.
My main class MouseMoveDrag is connected to a document class
and it is directed to the as file.
However I keep getting this message
"1120: Access of undefined property ball.

I'm wrestling with a similar problem at the moment mate.
1120: Access of undefined property ball
This error simply means that it can't find the specified
object, in this case "ball".
What you have to do is rename the init function in
MouseMoveDrag.as to something else, make it public and in Ball.as
you have to call the renamed init function in MouseMoveDrag and
pass the ball sprite.
So, you might want to have at the end of your init function
in Ball,as:
renamedInitFunction(ball);
and your renamed function header in MouseMoveDrag will look
something like this:
public function renamedInitFunction(ball):void {
If you get an error saying could not find
renamedInitFunction(ball) from Ball.as, then try making Ball.as
extend MouseMoveDrag, so like this:
public class Ball extends MouseMoveDrag {
This simply means that Ball will inherit properties from
MouseMove Drag including functions ;)

Similar Messages

  • Calling arraylist from another class - help please!!

    Hey, I need some help calling my arraylist from my GUI class, as the arraylist is in the 'AlbumList' class and not in the 'GUI' class i get the error 'cannot find symbol', which is pretty obvious but i cannot figure how to get around this problem. help would be greatly appreciated.
    i have written ***PROBLEM*** next to the bad line of code!
    Thanks!!
    public class Album
        String artist;
        String title;
        String genre;
        public Album(String a, String t, String g)
            artist = a;
         title = t;
            genre = g;
         public String getArtist()
            return artist;
        public String getTitle()
            return title;
         public String getGenre()
            return genre;
    public class AlbumList
        public ArrayList <Album> theAlbums;
        int pointer = -1;
        public AlbumList()
            theAlbums = new ArrayList <Album>();
        public void addAlbum(Album newAlbum)
         theAlbums.add(newAlbum);
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GUI extends JFrame
        public int max = 5;
        public int numAlbums = 4;
        public int pointer = -1;
        public GUI ()
            super("Recording System");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel main = new JPanel();
            JPanel panel1 = new JPanel();
            panel1.setLayout(new GridLayout(3,2,0,0));
            JPanel panel2 = new JPanel();
            panel2.setLayout(new GridLayout(1,2,20,0));
            final JLabel artistLBL = new JLabel("Artist: ");
            final JLabel titleLBL = new JLabel("Title: ");
            final JLabel genreLBL = new JLabel("Genre: ");
            final JTextField artistFLD = new JTextField(20);
            final JTextField titleFLD = new JTextField(20);
            final JTextField genreFLD = new JTextField(20);
            final JButton nextBTN = new JButton("Next");
            nextBTN.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    pointer++;
                    artistFLD.setText(theAlbums.get(pointer).getArtist());       ***PROBLEM***
                    titleFLD.setText("NEXT");
                    genreFLD.setText("NEXT");
            final JButton prevBTN = new JButton("Prev");
            prevBTN.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    pointer--;
                    artistFLD.setText("PREVIOUS");
                    titleFLD.setText("PREVIOUS");
                    genreFLD.setText("PREVIOUS");
         panel1.add(artistLBL);
            panel1.add(artistFLD);
            panel1.add(titleLBL);
            panel1.add(titleFLD);
            panel1.add(genreLBL);
            panel1.add(genreFLD);
            panel2.add(prevBTN);
            panel2.add(nextBTN);
            main.add(panel1);
            main.add(panel2);
            setVisible(true);
            this.getContentPane().add(main);
            setSize(500, 500);
    -----------------------------------------------------------------------Thanks!!
    Edited by: phreeck on Nov 3, 2007 8:55 PM

    thanks, it dosnt give me a complication error but when i press the button it says out of bounds error, and i think my arraylist may be empty possibly even though i put this data in.. this is my test file which runs it all.
    any ideas? thanks!!
    public class Test
        public static void main(String []args)
            AlbumList a = new AlbumList();
            String aArtist = "IronMaiden";
            String aTitle = "7thSon";
            String aGenre = "HeavyMetal";
            Album newA = new Album(aArtist, aTitle, aGenre);
            a.addAlbum(newA);
            aArtist = "LambOfGod";
            aTitle = "Sacrament";
            aGenre = "Metal";
            Album newB = new Album(aArtist, aTitle, aGenre);
            a.addAlbum(newB);
            aArtist = "JohnMayer";
            aTitle = "Continuum";
            aGenre = "Guitar";
            Album newC = new Album(aArtist, aTitle, aGenre);
            a.addAlbum(newC);
            aArtist = "StillRemains";
            aTitle = "TheSerpent";
            aGenre = "Metal";
            Album newD = new Album(aArtist, aTitle, aGenre);
            a.addAlbum(newD);
         GUI tester = new GUI();
    }

  • Calling a function from another class - help!

    I realize that this is probably a basic thing for people who have been working with JavaFX for a while, but it is eluding me, and I have been working on it for over a week.
    I need to call a function that is in another class.  Here's the deal.  In EntryDisplayController.java, there are 2 possible passwords that can be accepted - one will give full access to the car, the second will limit functions on the car.  So when a password is entered and verified as to which one it is, I need to call a function in MainDisplayController.java to set a variable that will let the system know which password is being used - full or restricted.
    So in MainDisplayController.java I have this snippet to see
    public class MainDisplayController implements Initializable, ControlledScreen {
        ScreensController myController;
        public static char restrict;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            // TODO
        public void setRestriction(){
            restrict = 0;
            restrictLabel.setText("RESTRICTED");
        public void clearRestriction(){
            restrict = 1;
            restrictLabel.setText("");
    And in EntryScreenDisplay.java I have this snippet:
    public class EntryDisplayController implements Initializable, ControlledScreen {
         @FXML
        private Label passwordLabel ;
        static String password = new String();
        static String pwd = new String("");
         ScreensController myController;
         private MainDisplayController controller2;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            setPW(pwd);    // TODO
         @FXML
        private void goToMainDisplay(ActionEvent event){
            if(password.equals ("123456")){
              controller2.clearRestriction();
               myController.setScreen(ScreensFramework.MainDisplayID);
               pwd = "";
               password = "";
               setPW(pwd);
            else if(password.equals ("123457")){
               controller2.setRestriction();
                myController.setScreen(ScreensFramework.MainDisplayID);
               pwd = "";
               password = "";
               setPW(pwd);
            else{
                password = "";
                pwd = "";
                setPW(pwd);
    When I enter the restricted (or full) password, I get a long list of errors, ending with
    Caused by: java.lang.NullPointerException
      at velocesdisplay.EntryDisplayController.goToMainDisplay(EntryDisplayController.java:60)
    Line 60 is where "controller2.setRestriction(); is.
    As always, thanks for any help.
    Kind regards,
    David

    You never set the controller2 variable to anything, which is why you get a null pointer exception when you try to reference it.
    public static variables (and even singletons) are rarely a good idea as they introduce global state (sometimes they can be, but usually not).
    If a static recorder like this can only have a binary value, use a boolean, if it can have multiple values, use an enum.
    Some of the data sharing solutions in dependency injection - Passing Parameters JavaFX FXML - Stack Overflow might be more appropriate.
    I also created a small framework for roll based solutions in JavaFX which perhaps might be useful:
    http://stackoverflow.com/questions/19666982/is-there-a-way-to-implement-a-property-like-rendered-on-javafx
    https://gist.github.com/jewelsea/7229260
    It was just something I hacked together, so it's not a fully polished solution and you probably don't need something quite so complex.
    What you need is a model class shared between the components of your application.  Dependency injection frameworks such as afterburner.fx can help achieve this in a fairly simple to use way.
    If you don't want to go with a dependency injection framework, then you could use either a static singleton model class for your settings or pass the model class using the mechanism in defined in the passing parameters link I provided.  For a model class example, see the ClickCounter class from this example.   That example doesn't use FXML, but to put it together with the passing parameters solution, for your restriction model, you would have something like the following:
       private class Restricted {
         private final ReadOnlyBooleanWrapper restricted;
         public Restricted(boolen isRestricted) {
           restricted = new ReadOnlyBooleanWrapper(isRestricted);  
         public boolean isRestricted() {
           return restricted.get();
         public ReadOnlyBooleanProperty restrictedProperty() {
           return restricted.getReadOnlyProperty();
    Then in your EntryDisplayController you have:
    @FXML
    public void goToMainDisplay(ActionEvent event) {
         // determine the restriction model as per your original code...
         RestictionModel restrictionModel = new RestrictionModel(<appropriate value>);
      FXMLLoader loader = new FXMLLoader(
      getClass().getResource(
       "mainDisplay.fxml"
      Stage stage = new Stage(StageStyle.DECORATED);
      stage.setScene(
       new Scene(
         (Pane) loader.load()
      MainDisplayController controller =
        loader.<MainDisplayController>getController();
      controller.initRestrictionModel(restrictionModel);
      stage.show();
    class MainDisplayController() {
      @FXML private RestrictionModel restrictionModel;
      @FXML private RestrictLabel restrictLabel;
      public void initialize() {}
      // naming convention (if the restriction model should only be set once per controller, call the method init, otherwise call it set).
      public void initRestrictionModel(RestrictionModel restrictionModel) {
        this.restrictionModel = restrictionModel;
         // take some action based on the new restriction model, for example
        restrictLabel.textProperty.bind(
          restrictionModel.restrictedProperty().asString()
    If you have a centralized controller for your navigation and instantiation of your FXML (like in this small FXML navigation framework), then you can handle the setting of restrictions on new screens centrally within the framework at the point where it loads up FXML or navigates to a screen (it seems like you might already have something like this with your ScreensController class).
    If you do this kind of stuff a lot, then you would probably benefit from a move to a framework like afterburner.  If it is just a few times within your application, then perhaps something like the above outline will give you enough guidance to implement a custom solution.

  • Preloader in Document Class Help.

    Hello,
    I want to know that how can I add a Preloader to my existing document class. In my FLA all content is on 1st Frame. I'm loading an external image to a MovieClip which is on 1st frame and on stage. My document class is working fine but when i try to add any preloading script, its not working...
    Can any one please help me in this regard..
    A Garden of Thanks.
    My Document Class is here...  (This was also a tutorial which I'm using..)
    package com.ahmad.bg
         //import all classes
         import caurina.transitions.Tweener;
         import flash.display.Loader;
         import flash.display.MovieClip;
         import flash.display.Sprite;
         import flash.display.StageAlign;
         import flash.display.StageDisplayState;
         import flash.display.StageScaleMode;
         import flash.events.Event;
         import flash.events.MouseEvent;
         import flash.net.URLRequest;
         public class MainClass extends MovieClip
              //create variables
              private var loader:Loader;
              private static const IMAGE_PATH:String = "bgs/bg.jpg";          
              public function MainClass() {
                   stage.align = StageAlign.TOP_LEFT;
                   stage.scaleMode = StageScaleMode.NO_SCALE;               
                   stage.addEventListener(Event.RESIZE, stageResize);          
                   //load external image
                   loader = new Loader();
                   loader.load(new URLRequest(IMAGE_PATH));
                   loader.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);
                   pic.addChild(loader);     
              private function showImage(e:Event):void
                   try {                              
                        e.target.content.alpha = 0;
                        Tweener.addTween(e.target.content, { alpha:1, time:1, transition:"easeOutSine" } );                    
                        e.target.content.smoothing = true;                              
                   } catch (e:Error) { };
                   stageResize();
              private function stageResize(e:Event=null):void
                   pic.x = 0;
                   pic.y = 0;
                   pic.scaleX = pic.scaleY = 1;               
                   if ((stage.stageHeight / stage.stageWidth) < pic.height / pic.width) {
                        pic.width = stage.stageWidth;
                        pic.scaleY = pic.scaleX;
                   } else {
                        pic.height = stage.stageHeight;                    
                        pic.scaleX = pic.scaleY;
                   pic.x = stage.stageWidth / 2 - pic.width / 2;
                   pic.y = stage.stageHeight / 2 - pic.height / 2;          
                   //my bottom navigation
                            bottomNav.x = Math.floor(stage.stageWidth / 2 - bottomNav.width / 2);
                   bottomNav.y = Math.floor(stage.stageHeight - bottomNav.height - 0);

    package com.ahmad.bg
         //import all classes
         import caurina.transitions.Tweener;
         import flash.display.Loader;
         import flash.display.MovieClip;
         import flash.display.Sprite;
         import flash.display.StageAlign;
         import flash.display.StageDisplayState;
         import flash.display.StageScaleMode;
         import flash.events.Event;
         import flash.events.MouseEvent;
         import flash.net.URLRequest;
         import flash.events.ProgressEvent;
         public class MainClass extends MovieClip
              //create variables
              private var loader:Loader;
              private static const IMAGE_PATH:String = "bgs/bg.jpg";          
              public function MainClass() {
                   stage.align = StageAlign.TOP_LEFT;
                   stage.scaleMode = StageScaleMode.NO_SCALE;               
                   stage.addEventListener(Event.RESIZE, stageResize);          
                   //load external image
                   loader = new Loader();
                   loader.load(new URLRequest(IMAGE_PATH));
                   loader.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);
                   loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, preload_image, false, 0, true);
                   private function preload_image(event:ProgressEvent):void
                          var per = int((event.bytesLoaded / event.bytesTotal) * 100);
                          pic.addChild(loader);
                          //make a textfield or preloader animation and assign this per to it.
              private function showImage(e:Event):void
                   try {                              
                        e.target.content.alpha = 0;
                        Tweener.addTween(e.target.content, { alpha:1, time:1, transition:"easeOutSine" } );                    
                        e.target.content.smoothing = true;                              
                   } catch (e:Error) { };
                   stageResize();
              private function stageResize(e:Event=null):void
                   pic.x = 0;
                   pic.y = 0;
                   pic.scaleX = pic.scaleY = 1;               
                   if ((stage.stageHeight / stage.stageWidth) < pic.height / pic.width) {
                        pic.width = stage.stageWidth;
                        pic.scaleY = pic.scaleX;
                   } else {
                        pic.height = stage.stageHeight;                    
                        pic.scaleX = pic.scaleY;
                   pic.x = stage.stageWidth / 2 - pic.width / 2;
                   pic.y = stage.stageHeight / 2 - pic.height / 2;          
                   //my bottom navigation
                   bottomNav.x = Math.floor(stage.stageWidth / 2 - bottomNav.width / 2);
                   bottomNav.y = Math.floor(stage.stageHeight - bottomNav.height - 0);
    Oh.. Thanks.. its working now... Thanks aloooooooooooooot.....
    Any other tip if you have a time to give me will be a greatful to you...
    Thanks again for your precious time.. I've seen your Awesome Portfolio at your website....

  • Exception class help

    Hi,
    i create exception class like it write in the sap help and when i want to send the exception with parameters to the ABOVE METHODS i don't susses  i just get the message without the parameter ?
    there is simple guideline how o transfer the exception with parameters?
    br
    Ricardo

    HI Uwe,
    Thanks,
    This is my sample code:
    This is the first method on the tree:
    the method name is create .
    INSERT (lt_table_name) FROM <ls_obj>.
        IF sy-subrc <> 0.
          RAISE EXCEPTION TYPE /cx_db_db_error
            EXPORTING
              textid     = cx_db_error=>create_failed
              table_name = lt_table_name.
        ENDIF.
    this method call to the above method - create .
    TRY.
            CALL METHOD lo_obj_create->create
              CHANGING
                is_bound_object = ls_obj_user.
          CATCH cx_db_error INTO lo_exc.
            "Create user failed. Throw an exception.
            RAISE EXCEPTION TYPE cx_db_error
              EXPORTING
                textid     = cx_db_error=>create_user_error
                previous   = lo_exc.
            result = lo_exc->get_text( ).
        ENDTRY.
    here in result i just get the massage without the table name that i export in the first method ,what i miss here ?
    Best Regards
    Ricardo

  • Trying to understand methods - calling methods within own class - help

    I'm trying to write a simple program to search for letters in a string. I'm having a ton op problems; java seems so complicated with a lot of rules.
    The main problem I'm having (for now) is calling a method within the same class as main.
    import java.io.*;
    class LookForLetters{
        public static void main(String[] args)
         int i = 0;     
         int j = 0;
         int l = 0;
         int m = 0;
         String question1 = "Enter the line to be searched"; 
         String question2 = "Enter the line to be searched";       
         returnResponse stringtosearch = new returnResponse(question1); // here's where my problem is
            char[] chartosearch = stringtosearch.toCharArray();
         returnResponse letterstofind = new returnResponse(question2);
            char[] chartofind = letterstofind.toCharArray();     
         int findlength = chartosearch.length();
         int searchlength = chartofind.length();
         int[] k = new int[searchlength];
         for(i = 0; i < findlength; i++)
             for(j = 0; j < searchlength; j++)   
              if(chartosearch[i] == chartofind[j])
                  k[l] = i;
                  l++;
                  System.out.print("T");
             System.out.print(i + " " + l);
                if(l == 0)
                    System.out.print(chartofind[i] + " is the not in the sentence.");
                    System.out.println();       
                else
                    System.out.print(chartofind[i] + " is the ");
                 for(m = 0; m < l; m++)
                     System.out.print(k[l] + " ");
                    System.out.print("letter of your sentence");
                    System.out.println();
                    l = 0;
        public String returnResponse(String question){
         String response = " ";
         System.out.print(question);
         try
             InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReaderbr = new BufferedReader(isr);
             response = br.readLine();            
         catch(IOException e)
             System.out.print("error");
         return response;
    }The compiler says that it can't find the returnResponse method. when I try to instantiate the whole class, it says the package is not included. Please help.

    JoachimSauer wrote:
    DaneWKim wrote:
    thank you very much for your response. I'm sure it's obvious that I'm really confused. I'm used to C and assembly programming, so the OO concepts are really foggy.That particular line doesn't even deal with any OO concept. But the fact that you already know C helps me give a (hopefully) more useful answer:
    What is the return type of the method you're trying to call?
    What is the type of the variable you want to assign the return value to?
    Are those compatible? Or even more general: do they both exist?I changed it to:
            String stringtosearch = returnResponse(question1);
            char[] chartosearch = stringtosearch.toCharArray();
         String letterstofind = returnResponse(question2);
            char[] chartofind = letterstofind.toCharArray();I guess I'm getting confused with medthods, class and types. There's a whole host of new vocabulary and rules with OO and java that have me a bit confused. I appreciate your help.

  • Stack class help

    hi i was wondering if anyone could help me, i keep getting 2 errors on the pop and push methods sayin it cannot find the variable.
    package labwork1;
    import java.util.*;
    * @author me
    public class Main
        public Main() {
        public static void main(String[] args)
          Stack stk = new Stack();
        public void help(String object)
            if(object.startsWith("-")){
                stk.pop();
            else{
                   stk.push(object);
    }

    ok i get that the scope of the stack is only in the
    main method, how would i solve this, so that the push
    and pop methods will work?Not sure what you are doing but:
    Declare it in the class as an instance variable.

  • Can't find textbox class - help please!

    I'm posting this again, in the hope that more people might help. I already know that the error means that the compiler can't find the class Textbox. I need to know why, because I've copied the relevant parts of the code from another app that builds fine. So why won't this build?
    I'm trying to write and build my first J2ME app. My code starts:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import java.lang.Math;
    public class TestMIDlet
    extends MIDlet
    implements CommandListener
    private Textbox tbMain;
    public void startApp()
    The build fails with numerous errors of which the first is:
    C:\WTK22\apps\TestMIDlet\src\TestMIDlet.java:9: cannot find symbol
    symbol : class Textbox
    location: class TestMIDlet
    private Textbox tbMain;
    with the caret under the 'T' of Textbox
    I don't understand what's wrong with this, as it's in many of the sample apps I've looked at.
    Thanks
    Ed

    Thanks very much!
    I've lost count of the times I've been caught by that case-sensitivity thing in Javascript. I thought it was just the first letter that had to be capitalised. Progress at last!

  • Need Classes help......

    Hi all,
    i was wondering if anyone can help me out with my code.
    i've got a class Desktop, and a class menu.
    the class Desktop contains the following...
    public class Desktop extends JFrame implements ActionListener{
    protected JDesktopPane  thedesktop;
    protected JMenuBar jMenuBar1;
    protected ..........and all elements declared here..
    public Desktop(){
    super("application");
    menu mymenu = new menu(); //class will build the menubar
    setJMenuBar(jMenuBar1); //adds menubar to jframe
    bla bla.......
    public static void main(String args[]){
    Desktop app = new Desktop(); //call constructor
    }the class menu is as follows
    public class menu extends Desktop{
    public menu() {
    jmenubar1 = new JMenuBar();
    //add all items to jmenubar1
    //all menus etc are declared in desktop, and initalized here
    // as this class extends desktop class
    }in desktop, i want the class menu to build the jmenubar for me,
    the i add the jmenubar with the line..setJMenuBar(jMenuBar1);
    both classes compile with no errors, but will not run, stalls on the commandline.
    can anyone see what i'm doing wrong ???
    it's something to do with the second class extending Desktop, and calling that constructor.
    is there a way around my problem ???
    thank you so much
    Paul

    Why don't you try this another way
    public class Desktop extends JFrame implements ActionListener{
             protected JDesktopPane thedesktop;
             private Menu myMenu;
          public Desktop(){
                 super("application");
                  myMenu = new Menu(); //class will build the menubar
                  setJMenuBar(myMenu.getMenuBar() );// call to the method in class Menu that will return a menubar
    public static void main(String args[]){
                Desktop app = new Desktop(); //call constructor
    class Menu extends Desktop{
         JMenuBar menuBar;
    public menu() {
            menuBar = new JMenuBar();
            // and all your stuff here
    public JMenuBar getMenuBar(){
            return menuBar;
    }

  • Importing Graph Class/help implement a weighted graph class

    Is there a way to import a graph structure into my java program so that I do not need to write my own graph class?
    If not, does anyone have a graph class that I can use? I've been trying to implement this program for the past few days..
    I'm having trouble implementing a weighted graph class. This is what I have so far:
    import java.util.ArrayList;
    import java.util.Queue;
    import java.util.*;
    public class Graph<T>
         private ArrayList<Vertex> vertices;
         int size = -1;
         public Graph() throws BadInputException
              ReadFile source = new ReadFile("inputgraph.txt");
              size = source.getNumberOfWebpages();
              System.out.println(size);
              vertices = new ArrayList<Vertex>();
         public int bfs(int start, int end) //breadth first search
              Queue<Integer> queue = new LinkedList<Integer>();
              if(start == -1 || end == -1)
                   return -1;
              if(start == end)
                   return 0;
              int[] d = new int[size];
              System.out.println(size + "vertices size");
              for(int i = 0; i < d.length; i++)
                   d[i] = -1;
              System.out.println(start + " START GRAPH");
              d[start] = 0;
              queue.add(start);
              while(!queue.isEmpty())
                   int r = queue.remove();
                   if(r == end)
                        return d[r];
                   for(EdgeNode ptr = vertices.get(r).head; ptr != null; ptr = ptr.next)
                        int neighbor = ptr.dest;
                        if(d[neighbor] == -1)
                             queue.add(neighbor);
                             d[neighbor] = d[r] + 1;
                             if(neighbor == end)
                                  return d[neighbor];
              return d[end];
         public boolean addEdge(int start, int end)
              Vertex v = new Vertex();
              v = vertices.get(start);
              EdgeNode temp = v.head;
              EdgeNode newnode = new EdgeNode(end, temp);
              v.head = newnode;
              return true;
         public void setRank(int vertex, double rank) //set the weights
              vertices.get(vertex).pageRank = rank;
         public double getRank(int vertex)
              return vertices.get(vertex).pageRank;
    If anyone could help. It would be greatly appreciated
    Edited by: brones on May 3, 2008 12:33 PM

    brones wrote:
    along with the rest of my code, I'm not sure how to implement it as a weighted graphA single list is not the proper way of representing a graph. An easy way to implement a graph is to "map" keys, the source-vertex, to values, which is a collection of edges that run from your source-vertex to your destination-vertex. Here's a little demo:
    import java.util.*;
    public class TestGraph {
        public static void main(String[] args) {
            WeightedGraph<String, Integer> graph = new WeightedGraph<String, Integer>();
            graph.add("New York", "Washington", 230);
            graph.add("New York", "Boston", 215);
            graph.add("Washington", "Pittsburgh", 250);
            graph.add("Pittsburgh", "Washington", 250);
            graph.add("Pittsburgh", "New York", 370);
            graph.add("New York", "Pittsburgh", 370);
            System.out.println("New York's edges:\n"+graph.getEdgesFrom("New York"));
            System.out.println("\nThe entire graph:\n"+graph);
    class WeightedGraph<V extends Comparable<V>, W extends Number> {
        private Map<V, List<Edge<V, W>>> adjacencyMap;
        public WeightedGraph() {
            adjacencyMap = new TreeMap<V, List<Edge<V, W>>>();
        public void add(V from, V to, W weight) {
            ensureExistenceOf(from);
            ensureExistenceOf(to);
            getEdgesFrom(from).add(new Edge<V, W>(to, weight));
        private void ensureExistenceOf(V vertex) {
            if(!adjacencyMap.containsKey(vertex)) {
                adjacencyMap.put(vertex, new ArrayList<Edge<V, W>>());
        public List<Edge<V, W>> getEdgesFrom(V from) {
            return adjacencyMap.get(from);
        // other methods
        public String toString() {
            if(adjacencyMap.isEmpty()) return "<empty graph>";
            StringBuilder b = new StringBuilder();
            for(V vertex: adjacencyMap.keySet()) {
                b.append(vertex+" -> "+getEdgesFrom(vertex)+"\n");
            return b.toString();
    class Edge<V, W extends Number> {
        private V toVertex;
        private W weight;
        public Edge(V toVertex, W weight) {
            this.toVertex = toVertex;
            this.weight = weight;
        // other methods
        public String toString() {
            return "{"+weight+" : "+toVertex+"}";
    }Note that I didn't comment it, so you will need to study it a bit before you can use it. If you have further question, feel free to ask them. However, if I feel that you did not take the time to study this example, I won't feel compelled to assist you any further (sorry to be so blunt).
    Good luck.

  • Custom classes, Help!

    hi every one,
    i really need help with custom classes, i just dont
    understand how to work with them. Can someone give me a small
    tutorial on how to write them, where to save them, and how to use
    them in another file.
    thank you very much

    search using google.

  • Will an Illustrator class help me understand Photoshop?

    Hi there,
    I realize I may have put the cart before the horse a bit, but I recently bought a copy of Photoshop, in hopes of learning how to use it to explore digital art and graphic creation.
    I know there are a ton of tutorials online, but I was considering taking a couple of inexpensive courses at community college too.  The school offers courses in Beginners Photoshop, but the next one is not until March.
    They do have a course on Illustrator though, that begins next week.
    I am wondering if it would be worthwhile to take that course, and if I could feasibly translate anything I learn in that class into Photoshop.  I figured at the least it would give me more of a feel for the Adobe programs in general, since I can't imagine their interfaces would be too terribly different.
    Thanks

    All Adobe programs have similiarites and I firmly believe that learning one will help you learn another.  Not only that, but Photoshop and Illustrator work well together, so it could be very useful for you to know both.

  • Inner classes help

    Hello, I was just wondering if someone can help me understand inner classes a little. If I have the following code:
    class Parent
    private String myString = new String(�I am parent�);
    public void writeIt()
         System.out.println(myString);
    public void displayIt()
         System.out.println((new InnerParent()).readMyString());
    class InnerParent
    public String readMyString()
    return myString;
    class Child extends Parent
    private String myString = new String(�I am child�);
    public void writeIt()
    System.out.println(myString);
    If we execute the following lines on the code
    Child myChild = new Child();
    Parent myParent = new Parent();
    myChild.writeIt();
    myParent.writeIt();
    myChild.displayIt();
    myParent.displayIt();
    Why does the following code display?
    I am child
    I am child
    I am parent
    I am parent
    ==
    Thanks!

    Child myChild = new Child();
    Parent myParent = new myChild();you again made a mistake,
    it should be
    Child myChild = new Child();
    Parent myParent = new Child();
    and now the output is
    I am child
    I am child
    I am parent
    I am parent
    because, myChild.writeIt(); displays the stirng, I am child, straightforward, when it comes to myParent.writeIt(); it displays the string I am child because, myParent is of the type Child() which has been casted back to Parent, since child extends parent this can be done, and so, it just behaves as if it is a child, and so it displays I am child. when it comes to myChild.displayIt(), it uses the string in the Parent class, since it extends Parent and it does not override that method, it has to use that string ,and so it displays I am Parent, and similarly for the myParent.displayIt(), also it displays I am Parent. Hope you Understood now.

  • Testing a class help needed

    Hi, I have to do the following :
    (1)Write a class called Student with the following private member variables:
    name [String]
    id [long]
    marks [float]
    (2)It must have the following methods:
    Methods to set name, set ID, and set marks
    Eg: public void setName(String newName) { … }
    Methods getName, getID, getMarks, eg:
    public long getID() {
    return id;
    (3)Note that the set and get methods do not normally display messages on screen. However, setMarks should display an error if the marks are not in the range 0 - 100, and set the member variable marks to 0.
    (4)To test the Student class, write a Test Class that creates a Student object and sets its name, ID and marks. The program should then display the student's name and marks in a message box.
    Its parts (3) and (4) Im having trouble with. Im not sure is part 3 correct and cant check it if I dont know what to do for part 4
    import javax.swing.JOptionPane;
    public class Student {
          * OBP
         private String name;  // Student's name.
         private long ID;  // Unique ID number for this student.
         private float marks;   // Grade
         private static int nextUniqueID = 0;
         // keep track of next available unique ID number
         Student(String newName)
              // Names Student, assigns the student a unique ID number
              name = newName;
              nextUniqueID++;
              ID = nextUniqueID;
         public String getName()
              return name;
         public long getID()
              return ID;
         public float getMarks()
              return marks;
         public void setName(String newName)
              name = newName;
         public void setID(long newID)
              ID = newID;
         public void setMarks(float newMarks)
              if (newMarks >=0 && newMarks <=100)
              marks = newMarks;
              else
                   JOptionPane.showMessageDialog(null, "Marks must be >=0 and <=100");
                   marks=0;
    }Im still new to this so be gentle :P
    Thanks

    pierrot_2 wrote:
    >
    No, not quite. It means, if you want to do this...
    Student mySt = new Student();... then your Student class has to have this...
    public class Student{
    public Student(){
    }... but it doesn't, so you can't.Just figured that one out.
    Huh? You're the one who said what the syntax should be with the private variables and public methods etc. So instead of doing this...
    mySt.setID;//wrong syntax... you have to follow the rules you wrote in the Student class definition...
    mySt.setID((long)34);//right syntax... but then on this particular method, your Student class has already assigned an ID value (in the constructor), so that undermines your own logic.Its an assignment, hence not technically my logic, just doing what it says and now trying to understand it.
    ... that's what I'd like to know.If you look at the first post its clearly an assignment I needed help with and it tells you what to do, which I (Yes, "I") did, so now trying to do the Test Class and understand it is the tricky bit.
    New Student class (so far):
    import javax.swing.JOptionPane;
    public class Student {
         private String name;  // Student's name.
         private long ID;  // ID number for this student.
         private float marks;   // Grade
         public Student()
         //Removed Unique ID part...Should this do something??
         public String getName()
              return name;
         public long getID()
              return ID;
         public float getMarks()
              return marks;
         public void setName(String newName)
              name = newName;
         public void setID(long newID)
              ID = newID;
         public void setMarks(float newMarks)
              if (newMarks >=0 && newMarks <=100)
                   marks = newMarks;
              else
                   JOptionPane.showMessageDialog(null, "Marks must be >=0 and <=100");
                   marks=0;
    }New Test class:
    import javax.swing.JOptionPane;
    public class Test{
         public static void main(String[] args)
              String newName = "Dave";
              long newID = 8731543;
              float newMarks = 1010;
              Student mySt = new Student();
              mySt.setName(newName);
              mySt.setID(newID);
              mySt.setMarks(newMarks);
              JOptionPane.showMessageDialog(null, "Name: " + newName + " Marks: " + newMarks );
    }The error message that mark is >100 comes up but then so does "Name: Dave Marks:1010.0" even though marks should be set to 0?
    Am I still far off? Its 2:45am here and I need to hand this in as soon as possible so am I in for an all nighter?

  • Class help needed.

    i have declared 3 variables in a class, x and y are coordiantres
    public class Robot
    private double x;
    private double y;
    private double Orientation;
    public Robot()
         x = 0;
         y = 0;
         Orientation = 0;
    public (double px, double py, double pOrientation)
         x = px;
         y= py;
         Orientation = pOrientation;
    public double getX()
    return x;
    public double getY()
    return y;
    public double getOrientation()
    return Orientation;
    public void turnRight (double pDeg) //Degrees
    Orientation= Orientation + pDeg;
    public void moveForward (double pDis)
    how do i get the moveforward i have been given the code written below. in the method also been given dx = d*sin(A) and dy = d*cos(A)
    aprreciate the help thanks
    double d=0;
    double dx=0;
    double dy=0;
    double radians=0;
    radians = Math.toRadians(A); //A is converted to radians
    dx=d* Math.sin(radians); //distance travelled in x
    dy=d* Math.cos(radians);//distance travelled in y
    stuck on what to do there, thanks

    >
    how do i get the moveforward i have been given the
    code written below. in the method also been given dx
    = d*sin(A) and dy = d*cos(A)
    aprreciate the help thanks
    double d=0;
    double dx=0;
    double dy=0;
    double radians=0;
    radians = Math.toRadians(A); //A is converted to
    radians
    dx=d* Math.sin(radians); //distance travelled in x
    dy=d* Math.cos(radians);//distance travelled in y
    A seems to be angle from the x axis that your robot is facing. Therefore replace it with your member variable orientation
    To get your new x, do x = x + dx;
    To get your new y, do y = y + dy;

  • Class help - simple q?

    Suppose I have three classes- Class 1, class 2 and class 3. Class 1 is the main class. Class 1 creates an object of class 2. Class 2 creates an object of class 3. Class 3 wishes to have a fileChooser dialog box disaplyed which requires the parent component to be called (ie, the frame in which the dialogue should appear.). However, this component is in class 1. How do I tell it to use the frame and set sizes from the main class (Class 1)?
    Please Please try to help - I'm really stuck!!

    Well, presumably the action starts with some kind of action in Class 1, which calls a method in class 2 which calls on in class three. You can add a reference to class 1 to each level of call as an extra argument.
    Alternatively you can add a constructor to classes 2 and 3 which stores a reference to class1 when you create new instances. Actually all classes have a construtor, if you don't specify one the compiler creates on with no arguments.

Maybe you are looking for

  • Are drives with the same name differentiated?

    I'm running OSX 10.6.8 and three external drives on which data is stored (a main drive, A-Data, and two backups). A friend may decide to help me with a project and to do so will have to have the same setup. Naming the drives on the second system is o

  • Parsing across multiple namespaces... best practice?

    Howdy all, here's my situation: I am attempting to create a simple interface to a particular type of webdav server which has some unusual XML data coming back, and need some advice on the best way to parse this XML. I have a generic "query" object wh

  • 5th gen 30 GB iPod & iCal

    My iPod says it's syncing my iCal calendar, but it's not. Anybody have a solution? Everything else works fine. Thanks. Tom Powerbook G4   Mac OS X (10.4.8)   1 Ghz PowerPC, 1 MB L3 cache

  • Changes in Bundle.js file are disappear after restarting the UCM

    Good Day, I add some javascript code in bundle.js file within the following path: domain_home\ucm\cs\weblayout\resources\bundle.js . the changes are reflected fine on the UCM, but once the UCM Server restated the changes are gone and the file revert

  • Extended Analytics template label issue

    I'm trying to create star schema via extended analytics from work space but getting below error 'Invalid Extn Analy templete label. Please provide a valid template label. ' I followed all steps provided on http://www.oracle.com/technetwork/middleware