Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Java Code Help - Calling Method

  1. #1
    Junior Member
    Join Date
    Sep 2009
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Java Code Help - Calling Method

    Hi everyone. I'm a new high schoolin' java student, working my way through this workbook. I'm trying to figure out how to call a method from another method. Here's what I need my code to do:

    Input number -> have a cubing method call the square method -> cube the results -> display resulting number.

    Here's what I have, but I can't figure out how to get Step3 to call the information produced by step2 out...And nothing prints out to the command line. Can someone please help?

    import java.util.Scanner;
    public class MyCode
    {
            public static void main(String[] args)
            {
                double entry;
                Scanner keyBoard = new Scanner(System.in);
                System.out.print("Enter a number which you wish" +
                        "to square, then cube: ");
                entry = keyBoard.nextDouble();
     
                System.out.print("The number chosen is ");
                System.out.println(entry);
     
     
            }
     
     
         public double stepTwo(double entry)
       {   double resultTwo;
           resultTwo = Math.pow(entry,2);
           return resultTwo;
       }
     
         public double stepThree()
         {
             double finalAnswer;
             return finalAnswer = resultTwo * resultTwo;
             System.out.println("The answer is: " + stepThree(finalAnswer) + " . ");
         }
     
    }


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java Code Help - Calling Method

    Simple, in fact you're already calling a few methods in your code. They just happen to be methods you didn't write

    The general from:

    method_name(method_parameters)

    method_name is the name of the method, and method_parameters are the arguments you pass to your method (0 or more, separated by commas).

    methods can also return ONE value (unless void, then method must return ZERO values). The value is returned using the return keyword (how convenient). However, even though a method can only return one value/run, it can have multiple return statements.

    ex.
    public static boolean isZero(int number)
    {
         // returns true if number is zero
         if (number == 0)
              return true;
         else
              return false;

    So how do you use the return value in the calling method? A simple way to think of it is this: take the entire method_name(method_parameters) and replace it with the return value
         int a = doIt();
         // say doIt() returns 5, the command can be thought of as looking like this:
        int a = 5;

    here, there are 2 return statements, but each run it is only possible that 1 return statement ever gets executed (can you see why?)

    Also, another thing about return statements: They stop the execution of that method and return back to the calling method.

    public static void doIt()
    {
         return;
         // this next line will never get executed
         System.out.println("You'll never see this!");
    }

    Because of this, some compilers (Eclipse and NetBeans, plus a few others) will throw a syntax error when you try to write statements that can can never be executed.

    So, let's fix your code. As a general rule of thumb, don't have "side-effects" in sub-methods. Side effects are things that performs some output (screen, sound, etc.), or ask for some input. There are some times this is unavoidable, but if it's avoidable, avoid it

    So, let's fix your code. I've put comments on places that have been changed
    import java.util.Scanner;
    public class MyCode
    {
            public static void main(String[] args)
            {
                double entry;
                Scanner keyBoard = new Scanner(System.in);
                System.out.print("Enter a number which you wish" +
                        "to square, then cube: ");
                entry = keyBoard.nextDouble();
     
                System.out.print("The number chosen is ");
                System.out.println(entry);
     
               // get the value squared
               double squared = square(value);
               // print it out
               System.out.println("The value squared is " + squared);
               // get the value cubed
               double cubed = cube(value);
               // print it out
               System.out.println("The value cubed is " + cubed);
            }
     
     
         // changed method name to make more sense
         public double square(double entry)
       {   
           double resultTwo;
           resultTwo = Math.pow(entry,2);
           return resultTwo;
       }
     
         // changed method name to make more sense
         public double cube(double number)
         {
             double finalAnswer;
             // a cube is just number * number_squared
             finalAnswer = number * square(number);
             return finalAnswer;
         }
     
    }
    Last edited by helloworld922; September 17th, 2009 at 01:04 AM.

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    KevinGreen (September 17th, 2009)

  4. #3
    Junior Member
    Join Date
    Sep 2009
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Java Code Help - Calling Method

    Thank you for your help. I'm still a little off, as I can't get it to work right.

               // get the value squared
               double squared = square(value);
               // print it out
               System.out.println("The value squared is " + squared);
               // get the value cubed
               double cubed = cube(value);
               // print it out
               System.out.println("The value cubed is " + cubed);

    These don't print; should in cube(value); value be my output from my two other methods (IE, square & cube?). NetBeans says it can't find the symbol? Thanks again.

  5. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java Code Help - Calling Method

    haha, i wasn't reading carefully

    it should be this:
               // get the value squared
               double squared = square(entry);
               // print it out
               System.out.println("The value squared is " + squared);
               // get the value cubed
               double cubed = cube(entry);
               // print it out
               System.out.println("The value cubed is " + cubed);

  6. #5
    Junior Member
    Join Date
    Sep 2009
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Java Code Help - Calling Method

    Thanks.

    NetBeans is still throwing an error: 'non-static meth cube(double) cannot be referenced from a static context'.

    What does that mean?

  7. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java Code Help - Calling Method

    Oh duh... I forgot about that. Add the keyword 'static' to your method signatures
    public static double cube(double value)
    public static double square(double value)

    the static keyword means you want the function to work "statically" rather than on instanced variables. Here's a brief explaination of static and instance:

    Java is completely object oriented. So, everything has to be run from an object. However, when the JVM starts, it creates a "static" version of each class. There is only one static version of each class/JVM. To call a static method, you use:
    className.staticMethodName(params);

    Instance variables are kind of like copies of the object. They have different values between objects, and must be created before they can be used. To create an instance variable, use the "new" keyword.
    new SomeObject();

    To call a method in an instanced object, you use the object variable handle:
    SomeObject a = new SomeObject();
    a.doIt();

    *Note: Java will let you use static methods/fields with instance variables, but realize that it is still operating on the static object, not the instance object. For this reason, if you're accessing something that's static, make it a habit to use the above mentioned method for static access.

Similar Threads

  1. Replies: 5
    Last Post: September 6th, 2009, 05:39 AM
  2. adding main method to a code
    By IDK12 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: August 31st, 2009, 09:52 PM
  3. Replies: 2
    Last Post: June 13th, 2009, 02:44 AM
  4. [SOLVED] How to call string in another class in java?
    By tazjaime in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 23rd, 2009, 10:31 AM