Calling a method from another class

In summary: Setter; // this is the new class i have to makeimport java.util.Random;public class OdometerSetter {private int [] odometer; // create new array for odometerprivate int startOdometer; // save the starting odometer valuepublic void setOdometer() {this.odometer = new int[6]; // create new array for odometerthis.startOdometer = 1 + randomNumber.nextInt( 9999 ); // sets
  • #1
ProPatto16
326
0
So this should be simple. but i don't know why it isn't working.

so, I have one class called OdometerBuilder with a method in it. (not a main)
inside that method is like 40 lines of code. I am required to take out that code and make it into a separate class and method, done that. Now i need to call that code from that method, back into the method in OdometerBuilder. NOTE: before i took out the code it all worked perfectly so i know the code is right. just can't seem to call it properly

as i understand, to call a method from another class you first create an instance of that class

Odometer odometerSetter = new Odometer();

odometerSetter is the object name, and Odometer is the class I am calling the method from. That line works fine.

then when calling the method the line is

odometerSetter.setOdometer();

the method in the Odometer class i want is called setOdometer.
however, in odometerBuilder i get an error saying

<package odometerSetter does not exist>

idientifier expected

NOTE: The line odometerSetter.setOdometer(); is INSIDE a method in OdometerBuilder. is that a problem? (the creation of the instance is NOT in any method)

I can post the code if needed, can condense the problem area to probably 100 lines, but someone will need to tell me how to use the code tags in here.

Thanks for any help!
 
Physics news on Phys.org
  • #2
Don't you think it would be a good idea to at least tell us what language you are using? How does your program know where "Package odometerSetter" is? How did you tell it that?
 
  • #3
Oh sorry, didn't know it made a difference! It's java. I havnt been doing this for long. And I'm using the netbeans IDE if that matters.

And as for package I'm not sure. Never heard anything about packages.

All my .java and .class files are kept in the same folder on my C drive. Then I just use the javac command in the command window to compile then execute the program.

Sorry that's all I really know about running the programs, it's how I've always done it.
 
  • #4
I'm not sure about Java, but in C++, you can access member functions via a NULL pointer to a class.

Code:
     pOdometerBuilder = (OdometerBuilder *)NULL;
     ... = pOdometerBuilder->MemberFunction( ... );

For C++, MemberFunction() may need to use special handling when the "this" pointer == NULL.

However, my guess is that you're supposed to include the OdometerBuilder class inside the Odometer class or to create a class that includes both.
 
Last edited:
  • #5
It would be helpful if you posted your code. I find your post very confusing to sort through.
 
  • #6
okay so let's see if i can get these code tags right.

first, this is the class with the code i had to pull out of the other one

Code:
import java.util.Random;

public class Odometer // method to generate a random number
{    
    private int [] odometer = new int[6]; // create new array for odometer 
    private int startOdometer;
                
        public void setOdometer()
        {
         
            Random randomNumber = new Random(); // generate new number
            startOdometer = 1 + randomNumber.nextInt( 9999 ); // sets range for between 0 and 10,000 and saves it under startOdometer
        
         
        
            int rem; // creates new int for calculations

            // split random number into its digits and display on odometer labels
            odometer[0] = startOdometer/100000;
            rem = startOdometer%100000;
         
            odometer[1] = rem/10000;
            rem = rem%10000;
        
            odometer[2] = rem/1000;
            rem = rem%1000;

            odometer[3] = rem/100;
            rem = rem%100;

            odometer[4] = rem/10;
            rem = rem%10;

            odometer[5] = rem/1;
        }
        
        public int[] readOdometer()
        {
            return odometer;
        }
        
        
                
} // end generateOdometer method

And now this is the code segment that the above came from

Code:
private void generateOdometer() // method to generate a random number
    {
    
        odometerSetter.setOdometer();
        
        endOdometer = startOdometer; // set endOdometer equal to startOdometer
        
        odometerJLabels[0].setText(Integer.toString( odometer[0] ));
        odometerJLabels[1].setText(Integer.toString( odometer[1] ));
        odometerJLabels[2].setText(Integer.toString( odometer[2] ));
        odometerJLabels[3].setText(Integer.toString( odometer[3] ));
        odometerJLabels[4].setText(Integer.toString( odometer[4] ));
        odometerJLabels[5].setText(Integer.toString( odometer[5] ));
                
    } // end generateOdometer method

the second piece of code is from a class called OdometerBuilder

i have the line: Odometer odometerSetter = new Odometer();
inside the OdometerBuilder class but outside any method

The line: odometerSetter.setOdometer();
is where i pulled out the method setOdometer from the first class. so now what i need to do it call that method setOdometer(); back into that spot in generateOdometer method. when its all in the one class in the positions i said then it all works. so i know its not the code, just the way its called back into there.

hope the code tags worked.

thanks
 
  • #7
ProPatto16 said:
i have the line: Odometer odometerSetter = new Odometer();
inside the OdometerBuilder class but outside any method

Double check that it is there, and before your method definition. I am able to compile and run a simplified version of this code without errors. I have three classes all in the same directory, compiled in the following order:

Code:
import java.util.Random;

public class Odometer // method to generate a random number
{    
    private int [] odometer = new int[6]; // create new array for odometer 
    private int startOdometer;
                
        public void setOdometer()
        {
         
            Random randomNumber = new Random(); // generate new number
            startOdometer = 1 + randomNumber.nextInt( 9999 ); // sets range for between 0 and 10,000 and saves it under startOdometer
        
         
        
            int rem; // creates new int for calculations

            // split random number into its digits and display on odometer labels
            odometer[0] = startOdometer/100000;
            rem = startOdometer%100000;
         
            odometer[1] = rem/10000;
            rem = rem%10000;
        
            odometer[2] = rem/1000;
            rem = rem%1000;

            odometer[3] = rem/100;
            rem = rem%100;

            odometer[4] = rem/10;
            rem = rem%10;

            odometer[5] = rem/1;
        }
        
        public int[] readOdometer()
        {
            return odometer;
        }
        
        

} // end class Odometer

Code:
public class OdometerBuilder
{
    public int [] odometer = new int[6];
    Odometer odometerSetter = new Odometer();
    public void generateOdometer() // method to generate a random number
    {
        odometerSetter.setOdometer();
        odometer = odometerSetter.readOdometer();                
    } // end generateOdometer method
} // end class OdometerBuilder

Code:
public class odometerprog {
    public static void main(String[] args) {
        OdometerBuilder odometerinstance = new OdometerBuilder();
        odometerinstance.generateOdometer();
	System.out.println(odometerinstance.odometer[0]);
        System.out.println(odometerinstance.odometer[1]);
        System.out.println(odometerinstance.odometer[2]);
        System.out.println(odometerinstance.odometer[3]);
        System.out.println(odometerinstance.odometer[4]);
        System.out.println(odometerinstance.odometer[5]);
    }
}
 
  • #8
Hmm. That's comforting and confusing. Comforting it works. So thanks for your time!
 
  • #9
If you are still having the same problem, perhaps you can tell us when the problem occurs (during compilation or runtime), what version of java you are using, and if the problem occurs when you are compiling, how you are compiling your classes (which directory are you in? What order are you compiling them in, etc.)
 
  • #10
okay so i created 3 new projects and put my java classes Odometer, OdometerTest (the main is in here), and OdometerBuilder. still got the same problem. i tried compiling them in all different orders, made no difference. i have an error on NetBeans on the left panel with the project lists when i hover my mouse over the project name it says "error parsing file" whatever that means.

Im going to post all 3 classes. i have no idea what else to try.

*** The error occurs during runtime, when the Start Button is clicked. because the action listener for the start button calls the method generateOdometer and in the generateOdometer method is the method call for the method from the other class.

so here goes

Code:
//
import java.util.Random;

public class Odometer // method to generate a random number
{    
    private int [] odometer = new int[6]; // create new array for odometer 
    private int startOdometer;
                
        public void setOdometer()
        {
         
            Random randomNumber = new Random(); // generate new number
            startOdometer = 1 + randomNumber.nextInt( 9999 ); // sets range for between 0 and 10,000 and saves it under startOdometer
        
         
        
            int rem; // creates new int for calculations

            // split random number into its digits and display on odometer labels
            odometer[0] = startOdometer/100000;
            rem = startOdometer%100000;
         
            odometer[1] = rem/10000;
            rem = rem%10000;
        
            odometer[2] = rem/1000;
            rem = rem%1000;

            odometer[3] = rem/100;
            rem = rem%100;

            odometer[4] = rem/10;
            rem = rem%10;

            odometer[5] = rem/1;
        }
        
        public int[] readOdometer()
        {
            return odometer;
        }
        
        
                
} // end generateOdometer method

Code:
// OdometerTest.java
// Used to test Odometer class

import javax.swing.JFrame; // import 

public class OdometerTest extends JFrame // class to run odometer class
{
    public static void main( String[] args ) // main method
    {
        OdometerBuilder odometerbuilder = new OdometerBuilder(); // create new odometer object
        odometerbuilder.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // create GUI
        odometerbuilder.setSize( 600, 300 ); // set size of frame
        odometerbuilder.setVisible( true ); // set visible
    } // end main method
} // end class


I have posted the Last class in the next post becuase i exceeded the 20,000 character limit

All your time is very much appreciated!
 
  • #11
here is the 3rd class. this is the class that includes the method call

Code:
// OdometerBuilder.java
// Simulates a simple car odometer

// import necessary components
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
import javax.swing.*;

public class OdometerBuilder extends JFrame // create GUI and add elements
{
    Odometer odometerSetter = new Odometer();
    
    private JPanel titleJPanel; // JPanel to attach title
    private JLabel title; // JLabel for title
    private JLabel[] odometerJLabels; // JLabel with array of space for odometer
    private JPanel titleAndOdometerJPanel; // JPanel to attach title panel and odometer panel to
    private JPanel odometerJPanel; // JPanel for Jlabel odometer to be placed on
    private JLabel prompt; // prompt to enter vehicle speed
    private JTextField inputField; // field for user to enter vehicle speed
    private JTextArea output; // window for displaying various outputs
    private JPanel clockJPanel; // JPanel for clock to be attached to
    private JLabel clock; // label of clock
    private JPanel buttonsJPanel; // JPanel to attach buttons to
    private JPanel westJPanel; // JPanel to attach clock, input and prompt onto
    private JPanel centerJPanel; // JPanel to attach west panel and output label onto
    private JPanel promptAndInputJPanel; // JPanel to attach prompt and input onto
    private JButton startTrip; // start trip button
    private JButton stopTrip; // stop trip button
    private JButton tripLog; // trip log button
    private JButton clear; // clear button
    private JButton exit; // exit button
    
    private int input = 0; // integer value for speed. set to 0 for error handling later
    private int[] odometer; // array of integers for odometer
    private int startOdometer; // starting odometer generated by random number
    private int endOdometer; // odometer value when stop trip is pressed
    private int distanceTravelled = 0; // distance travelled, set to 0 for error handling
    
    private String startTime; // time of system clock at beginning of trip
    private String stopTime; // time of system clock at end of trip
    
    private Timer clockTimer; // timer object for the clock
    private Timer odometerTimer; // timer object for the odometer
    private final int CLOCK_DELAY = 1000; // 1000 milliseconds = 1 second delay
    private int ODOMETER_DELAY; // delay for odometer defined later on
    
    public OdometerBuilder() // method to build the GUI
    {
        titleAndOdometerJPanel = new JPanel(); // creates panel
        titleAndOdometerJPanel.setBorder(BorderFactory.createMatteBorder(
                                    5, 5, 5, 5, Color.yellow)); // adds a yellow border to panel
        titleAndOdometerJPanel.setLayout( new GridLayout(2,1 ) ); // set layout of JPanel     
        
        titleJPanel = new JPanel(); // creates panel for title
        titleJPanel.setBorder(BorderFactory.createMatteBorder(
                                    0, 0, 5, 0, Color.yellow)); // adds yellow border
        title = new JLabel( "Trip Logging System" ); // create label for title
        title.setFont(new Font("Arial", Font.BOLD, 16)); // set font and size of title
        title.setForeground( Color.BLUE ); // set colour of title
        title.setHorizontalAlignment( JLabel.CENTER ); // set title to center of JLabel
        titleJPanel.add( title ); // add title to JPanel
        titleAndOdometerJPanel.add( titleJPanel ); // add titleJPanel to titleAndOdometerJPanel
        
        odometerJLabels = new JLabel[ 6 ]; // create array for odometer digits
        odometerJPanel = new JPanel(); // create JPanel for odometer labels
        odometerJPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0)); // create empty border to add space between components
        odometerJPanel.setLayout( new GridLayout() ); // set layout of odometer panel
        
        // the following sets labels to 0, colour to blue and size of font.
        odometerJLabels[0] = new JLabel ("0");
        odometerJLabels[0].setForeground( Color.BLUE );
        odometerJLabels[0].setFont(new Font("Arial", Font.BOLD, 16));
        odometerJLabels[1] = new JLabel ("0");
        odometerJLabels[1].setForeground( Color.BLUE );
        odometerJLabels[1].setFont(new Font("Arial", Font.BOLD, 16));
        odometerJLabels[2] = new JLabel ("0");
        odometerJLabels[2].setForeground( Color.BLUE );
        odometerJLabels[2].setFont(new Font("Arial", Font.BOLD, 16));
        odometerJLabels[3] = new JLabel ("0");
        odometerJLabels[3].setForeground( Color.BLUE );
        odometerJLabels[3].setFont(new Font("Arial", Font.BOLD, 16));
        odometerJLabels[4] = new JLabel ("0");
        odometerJLabels[4].setForeground( Color.BLUE );
        odometerJLabels[4].setFont(new Font("Arial", Font.BOLD, 16));
        odometerJLabels[5] = new JLabel ("0");
        odometerJLabels[5].setForeground( Color.BLUE );
        odometerJLabels[5].setFont(new Font("Arial", Font.BOLD, 16));
        
        // add labels to odometer panels
        odometerJPanel.add( odometerJLabels[0] );
        odometerJPanel.add( odometerJLabels[1] );
        odometerJPanel.add( odometerJLabels[2] );
        odometerJPanel.add( odometerJLabels[3] );
        odometerJPanel.add( odometerJLabels[4] );
        odometerJPanel.add( odometerJLabels[5] );
         
        titleAndOdometerJPanel.add( odometerJPanel ); // adds odometer panel to titleAndOdometerJPanel
        
        prompt = new JLabel( "Enter vehicle speed(kmph):   " ); // prompt to user
        prompt.setForeground( Color.BLUE ); // set colour of prompt
        inputField = new JTextField( 5 ); // create new input field to accept speed
        inputField.addActionListener( new OdometerBuilder.InputHandler() ); // creates actionlistener to handle input from user
        
        clockJPanel = new JPanel(); // creates new jpanel to attach clock to
        clockJPanel.setLayout( new BorderLayout() ); // sets layout to borderlayout
        clockJPanel.setBorder(BorderFactory.createMatteBorder(
                                    1, 0, 0, 0, Color.gray)); // adds a border onto clock panel
        clock = new JLabel( "00:00:00" ); // sets clock to 00:00:00 initially
        clock.setFont(new Font("Arial", Font.BOLD, 16)); // sets fonts and size
        clock.setForeground( Color.BLUE ); // sets colour of clock
        clock.setHorizontalAlignment( JLabel.CENTER ); // sets clock to the center of the jpanel
        clockJPanel.add( clock, BorderLayout.CENTER ); // adds clock to clock panel
        
        output = new JTextArea( "" ); // creates new area for output
        output.setBorder(BorderFactory.createMatteBorder(
                                    0, 1, 0, 0, Color.gray)); // adds a border to output field
        
        promptAndInputJPanel = new JPanel(); // creates new panel for prompy and input
        promptAndInputJPanel.setBorder(BorderFactory.createEmptyBorder(25, 5, 25, 5)); // creates empty border to control size of components
        promptAndInputJPanel.setLayout( new BorderLayout() ); // sets layout
        promptAndInputJPanel.add( prompt, BorderLayout.WEST ); // adds prompt to the west of panel
        promptAndInputJPanel.add( inputField, BorderLayout.CENTER ); // adds input to center of panel
        
        westJPanel = new JPanel(); // creates panel for some components
        westJPanel.setLayout( new BorderLayout() ); // sets layout
        westJPanel.add( promptAndInputJPanel, BorderLayout.NORTH ); // adds prompt and input to north of west panel
        westJPanel.add( clockJPanel, BorderLayout.CENTER ); // adds clock to center of west panel
        
        centerJPanel = new JPanel(); // creates center panel
        centerJPanel.setBorder(BorderFactory.createMatteBorder(
                                    0, 5, 5, 5, Color.yellow)); // adds a yellow border to center panel
        centerJPanel.setLayout( new GridLayout(1,2) ); // sets layout of center panel
        centerJPanel.add( westJPanel ); // adds west panel to center panel 
        centerJPanel.add( output ); // adds output to center panel
        
        buttonsJPanel = new JPanel(); // creates buttons panel
        buttonsJPanel.setBorder(BorderFactory.createMatteBorder(
                                    0, 5, 5, 5, Color.yellow)); // adds yellow border to buttons panel
        buttonsJPanel.setLayout( new GridLayout() ); // sets layout of buttons panel
        
        startTrip = new JButton( "Start Trip" ); // creates new jbutton for start trip
        startTrip.addActionListener( // action listener for startTrip button
            new ActionListener() // creates a new ActionListener    
            {   
                public void actionPerformed(ActionEvent e) // action performed method for startTrip button
                { 
                    if ( input == 0 ) // if input is still 0, displays following message
                    {
                        output.setText( "A Speed value between 1-150kmph "
                                + "\nmust be entered before trip can begin." );
                    } // end if statement
                    else // if input has been set, the following occurs
                    {
                        output.setText( "" ); // resets outputJLabel after setting speed
                        generateOdometer(); // generate new random number for odometer
                        startOdometerTimer(); // calls method to start odometer timer
                        String timeformat = "HH:mm:ss"; // sets format for clock display       
                        SimpleDateFormat obDateFormat = new SimpleDateFormat(timeformat); // creating time format
                        Calendar time = Calendar.getInstance(); // get systems time
                        clock.setText( obDateFormat.format( time.getTime()) ); // display systems time
                        startTime = clock.getText(); // saves systems time into startTime variable
                        startClockTimer(); // start timer for clock
                    } // end else
                } // end actionPerformed method for start trip JButton    
            });// end new ActionListener
        
        stopTrip = new JButton( "Stop Trip" ); // create new button for stop trip
        stopTrip.addActionListener( // adds action listener
            new ActionListener() // creates new action listener
            {
                public void actionPerformed(ActionEvent e) // method for action listener
                {
                    if ( startOdometer == 0 ) // if startOdometer is still 0, display message
                    {
                        output.setText( "Trip needs to begin first."
                                + "\nEnter a Speed and click Start Trip." );
                    } // end if
                    else // when start odometer is set approproately
                    {    
                        stopClockTimer(); // stops timer for clock
                        stopOdometerTimer(); // stops timer for odometer
                        distanceTravelled(); // calls method to calculate distance travelled
                    } // end else
                } // end method for action listener
            }); // end action listener
        
        tripLog = new JButton( "Trip Log" ); // creates new button for trip log
        tripLog.addActionListener( // adds new action listener
            new ActionListener() // creates new action listener
            {
                public void actionPerformed(ActionEvent e)
                {
                    if ( distanceTravelled == 0 ) // if distance traveled is still 0, display following message
                    {
                        output.setText( "No trip recorded. "
                                + "\nEnter a Speed to begin trip." );
                    } // end if
                    else // if user has set speed, the following is displayed
                    {
                        output.setText( String.format( 
                            "TRIP LOG"
                            + "\nSpeed: " + input + "kmph"
                            + "\nEnd Meter Reading: " + endOdometer
                            + "\nStart Meter Reading: " + startOdometer
                            + "\nDistance Travelled (m): " + distanceTravelled + "metres"
                            + "\nStart Time: " + startTime
                            + "\nStop Time: " + stopTime )); 
                    } // end else
                } // end method for action listener
            }); // end action listener
        
        clear = new JButton( "Clear" ); // create new button for clear
        clear.addActionListener( // add action listener for clear
            new ActionListener() // creates new action listener
            {
               public void actionPerformed(ActionEvent e) // method for clear button
               {
                   input = 0; // sets input back to 0
                   startOdometer = 0; // reset to 0 for error handling
                   clock.setText( "00:00:00" ); // resets clock label to 00:00:00
                   inputField.setText( "" ); // clears input field
                   inputField.setEditable( true ); // unlocks input field
                   output.setText( "" ); // clears output field
                   resetOdometer(); // calls reset odometer method to reset labels to 0
               } // end method for action listener
            }); // ends action listener
        
        exit = new JButton( "Exit" ); // creates new button for exit
        exit.addActionListener( // adds new action listener for exit
            new ActionListener() // creates new action listener
            {
               public void actionPerformed(ActionEvent e) // method for exit button
               {
                   exitWindow(); // method call to close window
               } // end method for exit action listener
            }); // end action listener
        
        // adds all the buttons to buttons panel
        buttonsJPanel.add( startTrip ); 
        buttonsJPanel.add( stopTrip );
        buttonsJPanel.add( tripLog );
        buttonsJPanel.add( clear );
        buttonsJPanel.add( exit );
        
        // panels to JFrane
        add( titleAndOdometerJPanel, BorderLayout.NORTH );
        add( centerJPanel, BorderLayout.CENTER );
        add( buttonsJPanel, BorderLayout.SOUTH );     
    } // end GUI constructor
    
    private class InputHandler implements ActionListener // handler for user input
    { 
        public void actionPerformed(ActionEvent event) // action performed method for user input 
        {
            input = Integer.parseInt(inputField.getText()); // retrieves users input
            if ( input > 0 && input <= 150 ) // if statement for appropriate input
            {
                inputField.setEditable( false ); // lock inputfield and display following message
                output.setText( String.format("Speed registered successfully.\n"
                        + "Click Start Trip.\nIf incorrect, click Clear and re-enter.") ); 
            } // end if
            else 
            {
                inputField.setText( "" ); // reset input field and display following message
                output.setText( String.format( "Speed must be 1-150kmph.\n"
                        + "Please re-enter." ));    
            } // end else    
        } // end actionPerformed method
    } // end ActionListener 
    
    private void generateOdometer() // method to generate a random number
    {
    
        odometerSetter.setOdometer();
        
        endOdometer = startOdometer; // set endOdometer equal to startOdometer
        
        odometerJLabels[0].setText(Integer.toString( odometer[0] ));
        odometerJLabels[1].setText(Integer.toString( odometer[1] ));
        odometerJLabels[2].setText(Integer.toString( odometer[2] ));
        odometerJLabels[3].setText(Integer.toString( odometer[3] ));
        odometerJLabels[4].setText(Integer.toString( odometer[4] ));
        odometerJLabels[5].setText(Integer.toString( odometer[5] ));
                
    } // end generateOdometer method


    public void startOdometerTimer() // method to start timer for odometer
    {
        ODOMETER_DELAY = 3600000/(input*1000); // delay for odometer timer
        odometerTimer = new Timer( ODOMETER_DELAY, new OdometerBuilder.OdometerHandler()); // creates new timer and handler
        odometerTimer.start(); // starts timer
    } // end method
    
    private class OdometerHandler implements ActionListener // handler for odometer timer
    {
        public void actionPerformed( ActionEvent actionEvent )
        {
        
        // the following occurs every time the timer wakes up
        endOdometer = endOdometer + 1; // adds one to odometer value
        
        int rem; // int for calculations

        // splits digits and sets into array and display new odometer on labels
        odometer[0] = endOdometer/100000;
        rem = endOdometer%100000;
        odometerJLabels[0].setText(Integer.toString( odometer[0] )); 

        odometer[1] = rem/10000;
        rem = rem%10000;
        odometerJLabels[1].setText(Integer.toString( odometer[1] ));

        odometer[2] = rem/1000;
        rem = rem%1000;
        odometerJLabels[2].setText(Integer.toString( odometer[2] ));

        odometer[3] = rem/100;
        rem = rem%100;
        odometerJLabels[3].setText(Integer.toString( odometer[3] ));

        odometer[4] = rem/10;
        rem = rem%10;
        odometerJLabels[4].setText(Integer.toString( odometer[4] ));

        odometer[5] = rem/1;
        odometerJLabels[5].setText(Integer.toString( odometer[5] ));
        } // end method for action listener
    } // end handler for odometer timer
    
    public void stopOdometerTimer() // method to stop odometer timer
    {
        odometerTimer.stop(); // stops odometer timer
    } // end method

    public void startClockTimer() // method to start timer for clock
    {
        clockTimer = new Timer( CLOCK_DELAY, new OdometerBuilder.TimerHandler() ); // creates new timer and new handler for clock timer
        clockTimer.start(); // starts clock timer
    } // end method to start clock timer
    
// JOIN THIS CODE AND THE CODE IN THE NEXT POST TOGETHER TO MAKE THE COMPLETE CLASS

I exceeded the 20,000 limit again
 
  • #12
the following code join onto the end of the code in the last post. so sorry

Code:
private class TimerHandler implements ActionListener // handler for clock
    {
        public void actionPerformed( ActionEvent actionEvent )
        {
            // sets format, retrieves system time and prints to label
            String timeformat = "HH:mm:ss";        
            SimpleDateFormat obDateFormat = new SimpleDateFormat(timeformat);
            Calendar time = Calendar.getInstance();
            clock.setText( obDateFormat.format( time.getTime()) );
        } // end method for timer handler
    } // end timer handler
    
    public void stopClockTimer() // method to stop clock timer
    {
        clockTimer.stop(); // stops clock timer
        stopTime = clock.getText(); // sets clock to stopTime for trip log
    } // end method to stop clock
    
    public void distanceTravelled() // method to calculate distance travelled
    {
        distanceTravelled = endOdometer - startOdometer; // calculates distance travelled
    } // end method for distance travelled
    
    public void resetOdometer() // method to reset the odometer when clear button is pressed
    {
        // resets all labels in odometer to 0
        odometerJLabels[0].setText( "0" );
        odometerJLabels[1].setText( "0" );
        odometerJLabels[2].setText( "0" );
        odometerJLabels[3].setText( "0" );
        odometerJLabels[4].setText( "0" );
        odometerJLabels[5].setText( "0" );
    } // end method to reset odometer
    
    public void exitWindow() // method for when exit button is pressed
    {
        this.dispose(); // closes window
    } // end method exit window
    
} // end class OdometerBuilder
 
  • #13
Can you put statements that output a message to the console for all lines in the region of the problem that are executed?

Chances are if it's something to do with the callback, it's probably got something to do with some data structure not actually existing or something that is referenced that doesn't exist, or has at least been de-referenced and released somehow.
 
  • #14
I thought that. The only thing the odometer class does is defines the array odometer[] and sends it back to the inputHandler method in odometerBuilder. But for some reason that doesn't happen
 
  • #15
When I run the above code and enter 13 as the speed (it is probably poor design to make the user press Enter before the Start trip button :wink:), The first error that occurs is:

Code:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at OdometerBuilder.generateOdometer(OdometerBuilder.java:285)
	at OdometerBuilder.access$300(OdometerBuilder.java:16)
	at OdometerBuilder$1.actionPerformed(OdometerBuilder.java:162)...

So, the first place I look is at line 285 of OdometerBuilder.java, and there I see you are calling the setText method of odometerJLabels[0]. So then I look to see where in your code odometerJLabels[0] gets set and changed, and I see it gets set to an object reference in your class constructor, and that reference does not seem to be detroyed anywhere. So thgen I look at the argument of your setText method call, and I see you referencing the "odometer" variable, but I don't see you setting the values of that integer array (or even the dimensions of it!) anywhere in the OdometerBuilderClass prior to this method call.
 
  • #16
The values of the integer array get initialized in Odometer.java and then get set in the OdometetBuilder, in the same method as the method call. Are you saying I should be setting the JLabels in the odometer class too? And not odometerBuilder?

I've only been writing java for a few months so I havnt really got the grasp of errors yet, what the command prompt spits back is gibberish to me, I know that's pretty poor for a programmer.

And the other thing to note is the dimensions of the array and the array itself is created in the odometer class also.

I can follow what your saying, but I'm not sure how to go about fixing it?
I appreciate all your help! Thanks heaps!
 
  • #17
ProPatto16 said:
The values of the integer array get initialized in Odometer.java and then get set in the OdometerBuilder, in the same method as the method call.

Do they really?

The "odometerSetter.setOdometer();" call sets the value of "odometer" locally, inside the odometerSetter object. To set "odometer" in your generateOdometer() method, I would expect to see something like

Code:
odometer = odometerSetter.readOdometer();


And the other thing to note is the dimensions of the array and the array itself is created in the odometer class also.

Yes, but these are local to the Odometer class.
 
  • #18
ProPatto16 said:
The values of the integer array get initialized in Odometer.java and then get set in the OdometetBuilder, in the same method as the method call. Are you saying I should be setting the JLabels in the odometer class too? And not odometerBuilder?

I've only been writing java for a few months so I havnt really got the grasp of errors yet, what the command prompt spits back is gibberish to me, I know that's pretty poor for a programmer.

And the other thing to note is the dimensions of the array and the array itself is created in the odometer class also.

I can follow what your saying, but I'm not sure how to go about fixing it?
I appreciate all your help! Thanks heaps!

The basic idea to keep on top of these problems is knowing how objects are referenced when they are passed somewhere: particularly for listeners and event handlers.

What you need to make sure you do is know not only when the objects are destroyed, but every single listener, event handler, class, etc that uses it and how it uses it.

If this is done implicitly (i.e. things are done as a result of other commands you do or simply by default or by other code that is working in the background), then this can be an absolute nightmare since it makes debugging a lot harder.

If it is explicit though, the idea is track every form of registration with the event handlers and the listeners and know how to make these things stop referencing objects.

I gaurantee that if you keep this in the back of your mind, you will save yourself a lot of trouble and frustration and it will make you a better programmer as a result.

If you ever do multi-threaded programming, you'll learn how important it is to be in this mindset because if you don't you'll get things crash not only demand, but also in ways that you can't effectively debug.
 
  • #19
Okay, so what I've done is created an object odometer array of the odometer class in odometerBuilder, but havnt set that object in odometerBuilder? So if I have a return method in the odometer class, I need to be creating an object instance of the odometer class and then calling both the setOdometer method and the return method?

So odometerSetter is an instance of the odometer class. Then I need to do something with it to create an instance of the odometer array that I want in odometerBuilder?

And the action listener for the start trip button is the first place it's used then odometer array is edited totally in odometer builder so once I get that array into odometerBuilder properly it should be fine to get chopped and changed after that right?
 
  • #20
ProPatto16 said:
Okay, so what I've done is created an object odometer array of the odometer class in odometerBuilder, but havnt set that object in odometerBuilder?

You've created a dynamic Integer array with the statement

Code:
private int[] odometer;

in your instance of the odometerBuilder class, but haven't set the dimensions or values of that array inside your instance of the odometerBuilder class, prior to the problem statement on line 285 of the odometerBuilder.java source.

So if I have a return method in the odometer class, I need to be creating an object instance of the odometer class and then calling both the setOdometer method and the return method?

Yes. The setOdometer method set the values (its dimensions are already defined) of the local (internal to your instance of the Odometer class) integer array "odometer". This variable is private, so the only way to access it externally (like from your instance of the OdometerBuilder class) is by having a public method which returns it as a parameter (like the readOdometer method).

So odometerSetter is an instance of the odometer class. Then I need to do something with it to create an instance of the odometer array that I want in odometerBuilder?

I'm not sure what you are asking here. The variable "odometer", in the OdometerBuilder class, is a dynamic integer array. Before you try to access the zeroth component of the array, you must at the least specify its dimensions, so that it has a zeroith component. That can be done either with a statement like

Code:
odometer = new int[6];

or by setting it equal to some other integer array (like the one in your instance of the Odometer class!) that has already been initialized/set.
 
Last edited:
  • #21
okay so i made some changes.
first up i made the two variables in the odometer.java class public.

then i changed the generateOdometer() method in odometerBuilder to the following

Code:
private void generateOdometer() // method to generate a random number
    {
    
        odometer = new int[6];
        
        odometerSetter = Odometer.setOdometer();
        odometer = odometerSetter.readOdometer();
        
        endOdometer = startOdometer; // set endOdometer equal to startOdometer
        
        odometerJLabels[0].setText(Integer.toString( odometer[0] ));
        odometerJLabels[1].setText(Integer.toString( odometer[1] ));
        odometerJLabels[2].setText(Integer.toString( odometer[2] ));
        odometerJLabels[3].setText(Integer.toString( odometer[3] ));
        odometerJLabels[4].setText(Integer.toString( odometer[4] ));
        odometerJLabels[5].setText(Integer.toString( odometer[5] ));
                
    } // end generateOdometer method

but then i got 2 ompilation errors.

1st: line 283 of OdometerBuilder: non-static method setOdometer() cannot be referenced from a static context
odometerSetter = Odometer.setOdometer();
2nd: same line same class: incompatible types
found: void
required: Odometer
odometerSetter = Odometer.setOdometer();

so i decided to change the two methods in odometer.java and combine them. i changed the return type of setOdometer() from void to int[] and put the return statement inside the method. so then the code for generateOdometer() became:

Code:
private void generateOdometer() // method to generate a random number
    {
    
        odometer = new int[6];
        
        odometer = odometerSetter.setOdometer();
        
        endOdometer = startOdometer; // set endOdometer equal to startOdometer
        
        odometerJLabels[0].setText(Integer.toString( odometer[0] ));
        odometerJLabels[1].setText(Integer.toString( odometer[1] ));
        odometerJLabels[2].setText(Integer.toString( odometer[2] ));
        odometerJLabels[3].setText(Integer.toString( odometer[3] ));
        odometerJLabels[4].setText(Integer.toString( odometer[4] ));
        odometerJLabels[5].setText(Integer.toString( odometer[5] ));
                
    } // end generateOdometer method

and now it compiles and runs and i can even press the start button ! :)

BUT, i can see the odometer array appears on the JLabels as it should, but as soon as the timer for the odometer "wakes up" and ticks it over it changes all the labels to 0 and then continues correctly from there. so there's an issue somewhere with the array inside the timer handler. do i need to create a new instance of the array in the timer as well so it can re-write every time the timer "wakes up" or would it be easier just to create something like odometeragain[] and make it equal to the odometer array and then use odometeragain[] for the rest of the handling and uses in odometerBuilder?

thanks heaps guys!
 
  • #22
okay I've figured the next bit out.
during runtime i wasnt able to click the stop button. so startOdometer variable must of been equal to zero. which was the reason why the labels reset to 0's after the timer started. then it turns out I've never got the int variable startOdometer from the odometer.java class into the OdometerBuilder.java class. the startOdometer variable is the random number generated in the odometer class. so bear with me while i look up how to get variables between classes.
 
  • #23
ProPatto16 said:
okay so i made some changes.
first up i made the two variables in the odometer.java class public.

This is generally a bad idea. Public variables can be changed directly from external code in ways that you may not want to allow. There is nothing wrong with declaring the "odometer" array as private; you can still get external read access to it by calling the readOdometer method (which returns the odometer array to the calling program/class).

then i changed the generateOdometer() method in odometerBuilder to the following

Code:
private void generateOdometer() // method to generate a random number
    {
    
        odometer = new int[6];
        
        odometerSetter = Odometer.setOdometer();
        odometer = odometerSetter.readOdometer();
        
        endOdometer = startOdometer; // set endOdometer equal to startOdometer
        
        odometerJLabels[0].setText(Integer.toString( odometer[0] ));
        odometerJLabels[1].setText(Integer.toString( odometer[1] ));
        odometerJLabels[2].setText(Integer.toString( odometer[2] ));
        odometerJLabels[3].setText(Integer.toString( odometer[3] ));
        odometerJLabels[4].setText(Integer.toString( odometer[4] ));
        odometerJLabels[5].setText(Integer.toString( odometer[5] ));
                
    } // end generateOdometer method

but then i got 2 ompilation errors.

1st: line 283 of OdometerBuilder: non-static method setOdometer() cannot be referenced from a static context
odometerSetter = Odometer.setOdometer();
2nd: same line same class: incompatible types
found: void
required: Odometer
odometerSetter = Odometer.setOdometer();

It's good to see that you added the line
Code:
odometer = odometerSetter.readOdometer();

but changing the previous line to

Code:
odometerSetter = Odometer.setOdometer();

makes no sense. The method setOdometer() is not a static method, so it cannot be called this way. You must first create an instance of the Odometer class and assign it to an object reference (which you have with the line "Odometer odometerSetter = new Odometer();" ), and then call it using that object reference (i.e. use odometerSetter.setOdometer(); instead of Odometer.setOdometer();). Also, unless you've changed the setOdometer() method, it does not return anything as a parameter, so it makes no sense to set odometerSetter equal to the result of the method call. The correct syntax is just

Code:
odometerSetter.setOdometer();

which is exactly what you had before.
 
  • #24
ah thanks! that syntax can get confusing. i did have it all working properly, i added a return method for the startOdometer int variable and it all worked sweet. but i have changed those other variables back to private (i was aware of the poor practise in changing it to public), re-seperated the setOdometer method to set and read methods, added the correct syntax and now it all works!

thanks so much! 5 star!
 

FAQ: Calling a method from another class

What is the purpose of calling a method from another class?

The purpose of calling a method from another class is to access functionality that is defined in that class. This allows for code reusability and organization, as well as promoting modular design.

How do you call a method from another class?

To call a method from another class, you need to first create an object of that class. Then, using dot notation, you can access the method and call it on the object.

Can you call a method from another class without creating an object?

No, you cannot call a method from another class without creating an object. The method belongs to the class, so it can only be accessed through an instance of that class.

Can you call a private method from another class?

No, you cannot call a private method from another class. Private methods can only be accessed within the same class they are defined in.

What happens if you call a method from another class that does not exist?

If you call a method from another class that does not exist, you will get a compilation error. This is because the compiler cannot find the method and therefore cannot execute the code.

Similar threads

Replies
2
Views
1K
Replies
1
Views
1K
Replies
3
Views
471
Replies
12
Views
2K
Replies
1
Views
904
Replies
3
Views
2K
Back
Top