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 12 of 12

Thread: Need help with declaring static method for code.

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help with declaring static method for code.

    Hi everybody I'm extremely new to java programming and was asked to do this >

    " The formula for finding the greatest common divisor of two positive integers x and y
    follows the Euclidean algorithm as follows:
    1. Subtract x from y repeatedly until y < x.
    2. Swap the values of x and y.
    3. Repeat steps 1 and 2 until x = 0.
    4. y is the greatest common divisor of the two numbers.

    Place the calculation for finding the divisor in a static method. You can use one loop
    for step 1 of the algorithm nested within a second loop for step 3.

    Assume that the user will enter valid integers for both numbers.

    The application should continue only if the user enters “y” or “Y” to continue. "





    Problem is, I can't figure out how to do that. I'm trying the best I can but it says it doesn't work. Can you tell me how to fix it?

    Here's what's specifically wrong with it


    1. Illegal start of expression , cannot find symbol, symbol class : class first number, location: class Greatest common division finder.

    2. Illegal start of expression, cannot find symbol, symbol class : class second number, location : class Greatest common division finder.

    3. int Greatestcommondivisionfinder = 0; < The assigned value is never used

    4. public static int Greatestcommondivisionfinder(firstNumber, secondNumber){ <identifier expected>













    package greatest.common.division.finder;
     
    import java.util.Scanner;
    import java.math.*;
     
    /**
    *
    * Marcus Davis
    */
    public class GreatestCommonDivisionFinder {
     
    /**
    * @param args the command line arguments
    */
     
     
    public static void main(String[] args) {
     
    // welcome the user to the program
    System.out.println("Greatest Common Division Finder");
    System.out.println(); // print a blank line
     
    //create a Scanner object and start a while loop
    Scanner sc = new Scanner(System.in);
    String choice = "y";
    while (choice.equalsIgnoreCase("y"))
    {
    //get input from user
     
    System.out.print("Enter first number: ");
    int firstNumber = sc.nextInt();
     
    System.out.println("Enter second number: ");
    int secondNumber = sc.nextInt();
    }
     
    //create static method
     
     
    int secondNumber = 0;
    int firstNumber = 0;
    int Greatestcommondivisionfinder = 0;
     
     
     
     
     
     
    /**
    *
    */
    public static int Greatestcommondivisionfinder(firstNumber, secondNumber){
     
    //subtract firstnumber from secondnumber
    int secondNumber = 0;
    int firstNumber = 0;
    int Greatestcommondivisionfinder = 0;
     
     
     
     
    if (firstNumber > secondNumber)
    {
     
    secondNumber -= firstNumber;
     
    firstNumber--;
    }
     
    else if (firstNumber <= secondNumber)
    {
    firstNumber -= secondNumber ;
     
     
    }
    if (secondNumber == 0);
    { Greatestcommondivisionfinder = (firstNumber);
     
    }
     
     
     
     
    //Display GreatestCommondivisionfinder
    String message =
    "Greatest Common Division Finder:" + Greatestcommondivisionfinder + "\n";
    System.out.println(message);
    return Greatestcommondivisionfinder;
    }





    Any suggestions???
    Last edited by Marcusjamaal; October 9th, 2012 at 02:20 PM.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help with declaring static method for code.

    Hi Marcusjamaal
    Please see the announcements page for use of code tags, and properly format your code in the post above.

  3. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with declaring static method for code.

    Quote Originally Posted by jps View Post
    Hi Marcusjamaal
    Please see the announcements page for use of code tags, and properly format your code in the post above.

    Thank you.

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help with declaring static method for code.

    You are welcome. Please note that the closing tag should not be the same as the opening tag. This is the reason the tags are visible in the post and the code is not treated as code. The correct closing tag is listed on the announcements page linked to above. Please edit the post and correct the code to be highlighted and properly formatted.

    I will also mention that your question could use some improvement.
    I can't figure out how to do that
    How to do what exactly?
    it says it doesn't work.
    What says what does not work?
    Can you tell me how to fix it?
    Surely you get the idea.
    If there is an error message, paste it with your post. Try to form your question to be more specific as to what is not working the way you expected, or what part you are having problems with.

  5. #5
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with declaring static method for code.

    Sorry Guys here's what's specifically wrong with it


    1. Illegal start of expression , cannot find symbol, symbol class : class first number, location: class Greatest common division finder.

    2. Illegal start of expression, cannot find symbol, symbol class : class second number, location : class Greatest common division finder.

    3. int Greatestcommondivisionfinder = 0; < The assigned value is never used

    4. public static int Greatestcommondivisionfinder(firstNumber, secondNumber){ <identifier expected>

  6. #6
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Need help with declaring static method for code.

    Quote Originally Posted by Marcusjamaal View Post
    ... here's what's specifically wrong with it
    What's wrong with it is a bunch of things. Here's a general form of the kind of program that you need:
    public class Whatever {
        public static void main(String [] args) {
     
            int firstNumber;
            int secondNumber;
     
            //
            // Code to get values of firstNumber and secondNumber
            //
     
            int value = lcm(firstNumber, secondNumber);
            System.out.println("lcm = " + value);
     
        } // End of main()
     
        static int lcm(int a, int b) {
     
            int retval;
     
            //
            // code that works on a and b to calculate and
            // store the result in retval.
            //
     
            return retval;
        } // End of lcm()
    } // End of class definition

    Check with examples in your book or class notes or whatever. In Java you simply don't define a new method inside another. Period.

    For variables that are parameters of a method, you declare the data type in the parameter list. Do not declare variables with the same name inside the method. You want to use the values passed in as arguments from the calling function, right?


    Cheers!

    Z
    Last edited by Zaphod_b; October 9th, 2012 at 03:08 PM.

  7. #7
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with declaring static method for code.

    Thank you Z! . Also yes I do. I'm confused by your message though, if I'm prompting the user to enter input for the value of the numbers, my code must differ from your code to get the first and second number right?
    Last edited by Marcusjamaal; October 9th, 2012 at 03:24 PM.

  8. #8
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Need help with declaring static method for code.

    Quote Originally Posted by Marcusjamaal View Post
    ... my code must differ from your code to get the first and second number right?
    My "code" as you call it was the merest outline of a program file that was intended to show how to organize a class into a main() method and a static method called by main().

    No part of my code was intended to replace what you had written, so if you already know how to define the variables and get values from the user, don't think that I meant for you to change that part.

    Bottom line:
    Get the values in main(), by hook or crook, and then use those values as arguments in calling your other static method.


    Cheers!

    Z
    Last edited by Zaphod_b; October 9th, 2012 at 03:39 PM.

  9. #9
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with declaring static method for code.

    Z

    heres an updated code...I can say I'm understanding you, but it's alot different then actually doing so...

    public static void main(String[] args) {
     
            // welcome the user to the program
            System.out.println("Greatest Common Division Finder");
            System.out.println();  // print a blank line
     
            //create a Scanner object and start a while loop
            Scanner sc = new Scanner(System.in);
            String choice = "y";
            while (choice.equalsIgnoreCase("y"))
            {
                //get input from user 
     
                System.out.print("Enter first number:        ");
                int firstNumber = sc.nextInt();
     
                System.out.println("Enter second number:     ");
                int secondNumber = sc.nextInt();
     
                int j = firstNumber;
                int i = secondNumber;
            }
     
        }
     
     
     
                //creat static method int j = firstNumber, int i = secondNumber;
     
     
          static int Greatestcommondivisionfinder (int j, int i)
          {
     
     
     
     
     
     
     
     
     
     
                while (j > i)
                {
     
                     i -= j;
     
                                    j--;
                }
     
                else if ( int j <= int i) 
                {
                       j -= i ;
                                      i--;
     
            }
                while ( i >= 1)
     
            {
                        j -= i ;
                                        i--;
     
                    }
     
                  if (  i == 0);
                { int Greatestcommondivisionfinder = (j); 
     
               }
     
     
     
     
                   //Display GreatestCommondivisionfinder
                    String message = 
                            "Greatest Common Division Finder:" + Greatestcommondivisionfinder + "\n";
                    System.out.println(message);
     
            }

  10. #10
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with declaring static method for code.

    I'm having these problems now with it.

    1. theres a problem with "else without if"

    2. while ( i >= 1) , cannot find symbol <identifier expected>

    3. Alot of number 2 for mutiple functions

  11. #11
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Need help with declaring static method for code.

    First of all: It's a really, really (really) Good Thing to define a function (method) like your GCD finder in such a way as it does one thing: Calculates the GCD and returns that value. Then the main() function calls that method and prints the result that is returned. (You don't have to do it this way, but that's the way that I will illustrate.)

    So the guts of your main() look like the following. I used a shorter name for the function. You can use anything you please. I, personally can't see the point of using "CalculateGCD" or ObtainGCDByEuclidsAlgorithm or stuff like that, but maybe you are supposed to use a particular name that was specified in the assignment.

    Anyhow, here's the part of main() that gets user values, calls the function and prints the value returned by the function.

                System.out.print("Enter first  number:        ");
                int firstNumber = sc.nextInt();
     
                System.out.print("Enter second number:     ");
                int secondNumber = sc.nextInt();
     
                System.out.println("Will find gcd of " + firstNumber +
                                   " and " + secondNumber);
     
                int result = Gcd(firstNumber, secondNumber);
                System.out.println("Result = " + result);

    In other words, there is no reason to have to make up new names for variables to use to call the function. You can use the names you already have.


    Secondly: Get into the habit of using indentation that is consistent, and it's a lot easier to match braces and see the program flow. (For example: to see whether an 'else' appears naked (without a corresponding 'if').


    Thirdly: I don't particularly like the wording of the algorithm in your first post, and I can see why people might have a problem following it.

    I'll give a description that makes more sense to me. This is pseudo-code not Java, but it leads to something that you can easily implement in any of a number of procedural languages. So you can compare notes with that C++ programmer down the hall.
    Function Gcd(a, b)
     
        IF a IS EQUAL TO 0
        THEN
            RETURN  b
        END IF
     
        // a was not equal to 0.  Must do a little work
        WHILE  b IS NOT EQUAL to 0
        LOOP
            IF a IS GREATER THAN b
            THEN
                SET a EQUAL TO a − b
            ELSE
                SET b EQUAL TO b − a
            END IF
        END LOOP // End of the while loop
        RETURN a


    So, here is the skeleton of the Gcd function in Java:
        //
        // A Java function starts like this: A return type, the name of the function,
        // and parameters in parentheses.
        // Each parameter has its own data type declaration.
        // If the function doesn't have any parameters, the parentheses are empty.
        //
        // I'll use a and b as the parameters, since that's what was used in the 
        // pseduo-code
        //
        static int Gcd(int a, int b)
        {
            if (a == 0) { // I"ll give you the first one. For everything else, fill in the "somethings"
                //Do something
            }
            // use a and b to calculate their gcd and return the value of the gcd
            while (something) {
                if (something) {
                    //something
                }
                else {
                    //something
                }
            }
            //something;
        } // End of Gcd()

    Now, the point is that the function works on its local copies of the values of parameters a and b. The values of a and b inside the function correspond to the arguments inside the parentheses the statement in main() that calls this function. I used the names of the arguments in main() of variables that you had already defined and given values to.

    Each argument should be the same type of variable as the corresponding parameter, but their names are arbitrary. I made the names inside the function a and b so that I could fill in the "somethings" directly from the pseudo-code.

    By the way, this method is called the "Euclidean algorithm" and the pseudo-code that I used is a slightly re-styled version of the example at Euclidean algorithm - wikipedia In spite of what some people seem to believe, I don't just make these things up and I don't pretend that I did. Really.

    If you examine the pseduo-code that I show above and compare with the description in your first post, I think you may conclude that it is implementing the GCD algorithm the way you are supposed to be doing. (At least that's what I conclude.) There are other ways of finding the GCD of two numbers.


    Cheers!

    Z

  12. #12
    Junior Member
    Join Date
    Oct 2012
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with declaring static method for code.

    Thanks Z! Wow, this is gonna help me a ton!

Similar Threads

  1. Replies: 1
    Last Post: April 3rd, 2012, 06:32 AM
  2. What's the difference between a static and non-static method?
    By wholegrain in forum Java Theory & Questions
    Replies: 4
    Last Post: February 23rd, 2012, 01:06 AM
  3. Declaring static character array
    By jts0541 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 1st, 2012, 09:44 AM
  4. non-static method cannot be referenced from a static context
    By Kaltonse in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 21st, 2010, 07:51 PM
  5. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM