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

Thread: how to write a function *method* in Java to reverse an Array using Groovy?

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

    Unhappy how to write a function *method* in Java to reverse an Array using Groovy?


    This is my solution:
    /*3)    Write a function called reverse that takes a char array and returns the array in reverse order.*/
     
    char [] band = char [4];
    band [0] = "I";
    band [1] = "N";
    band [2] = "X";
    band [3] = "S";
     
    band [] = reverse (band []);
     
    def char [] reverse (char [] favband) {
     //char [] favband = new char [band.length];
     
     char [] newarray = new char [band.length];
     
     for (int i = band.length; i >=0; i--) {
     
      for (int j =0; j < band.length; j++) {
      favband [i] = newarray [j];
      }
     }
      return favband;
    }

    I keep updating the code but nothing helps. Thx
    Last edited by helloworld922; October 16th, 2012 at 06:36 PM.


  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: how to write a function *method* in Java to reverse an Array using Groovy?

    This is a Java programming forum, not a Groovy programming forum. We can try to help you as far as your algorithm is concerned but understand that to someone like me (someone who knows Java but doesn't know Groovy), I can't help you figure out if you have the syntax and semantics right.

    You may want to try your luck with a Groovy-specific forum or over at Stack Overflow where they are more likely to have someone more capable of helping you.

    As far as general help goes, what is the program doing? Add a few print statements (or use a debugger) to figure out what the code is doing at each step along the way. Try pretending you are the computer and execute the program by hand on a piece of paper.

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

    Default Re: how to write a function *method* in Java to reverse an Array using Groovy?

    but we use Java, and the only difference between functions and methods is
    def + return type + name of the function

  4. #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: how to write a function *method* in Java to reverse an Array using Groovy?

    It does look vaguely familiar and we'll try to help you, but I just wanted you to understand that our advice won't necessarily be correct concerning semantics and such.

    For example,

    char [] band = char [4];
    In Java this is a compile error. You must use the new keyword to create a new array. I have no idea if that's the same in Groovy or not. I'm not sure if this is what you meant by your program isn't working or not, you didn't say what is actually wrong with the code (are you getting compile errors? Runtime errors? Wrong results? Which ones?).

    I can tell though that your algorithm for reversing the array isn't quite right. Try working out by hand with a piece of paper how you would reverse an array.

  5. #5
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: how to write a function *method* in Java to reverse an Array using Groovy?

    I keep updating the code but nothing helps
    Can you clarify what you mean by this? Are there exceptions being thrown? There are syntax errors within the code you posted, which should result in an exception (for instance the code noted by helloworld)

  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: how to write a function *method* in Java to reverse an Array using Groovy?

    Quote Originally Posted by Cyclist View Post
    but we use Java..
    First of all:
    Groovy != Java

    Then, looking at your "code"

    1. There are, by my count, five lines that will cause groovy compiler errors. (Maybe more---I got tired of counting.)

    2. After making corrections to eliminate compiler errors, there is a line that is guaranteed to cause a runtime error.

    3. After making a simple change to eliminate the runtime error, I see that there is an assignment statement that results in the return value being an array of zero bytes.

    4. If that line is corrected, the function returns the original array and not the new array.

    5. If the return statement is corrected you will discover that the returned array is not the reverse of the original array, but has copied the last char of the original array to all positions of the return value.

    6. Etc.


    After correcting compiler errors, if you want to see why it is not working, put some println() and/or printf() statements in the code to see what is copying and where. If something happens that you don't understand, post the code and post the exact ouput or error message or whatever.

    For example:
          System.out.printf("Setting favband[%d] = newarray[%d] = '%c' (%d decimal)\n", i, j, newarray[j], (int)newarray[j]);
          favband[i] = newarray[j];

    Notes:

    1. There is various "getting started with groovy" documentation and there are tutorials for groovy, all of which are linked from the groovy mother lode at groovy.codehaus.com

    2. There is at least one active forum for Groovy. It's at nabble.com and is linked from the Groovy home page. Perhaps helpers there would be more tuned in to assisting Groovy beginners. I mean, it's OK to post here in the "Other Programming Languages" partition of this Java site, but you may find that there are more eager Groovy helpers on a Groovy forum than there are on a Java forum.

    If you do post, then the best chances for getting assistance would be to follow form.

    • Post the code. Post the entire code so that we can try to walk you through the debugging process.

    • Tell us exactly what happened---compiler error(s), runtime error(s), not getting expected output, whatever...

    • If there are compiler messages, paste the entire message into your post. Don't abbreviate; don't paraphrase.

    • Tell us exactly what you don't understand about the behavior.


    It's also a Good Idea to tell us about your setup: What version of Groovy? What Operating System (and what version)? Sometimes it makes a difference to people who would like to help.


    Cheers,

    Z
    Last edited by Zaphod_b; October 17th, 2012 at 10:42 AM.

  7. #7
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Cool Re: how to write a function *method* in Java to reverse an Array using Groovy?

    Try creating a Java class with a main method. Then create a method to handle the reversal and call it from main.

    Declare your array in main as follows: char[] band = { 'I', 'N', 'X', 'S' };

    You can also declare it on separate lines, if you prefer.
    char [] band = new char[4];
    band[0] = 'I';
    band[1] = 'N';
    band[2] = 'X';
    band[3] = 'S';

    (Bear in mind that a char [] uses single quotes ' ' and not " " <-- those are for Strings.)

    Ideally you would need a loop to print the result to see if it is correct.

    Let's see you make a start and we can help further. (Hint) There is also an error in the for loop. It's going beyond the boundaries of the array (size).

  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: how to write a function *method* in Java to reverse an Array using Groovy?

    Quote Originally Posted by Starstreak View Post
    Try creating a Java class with a main method. Then create a method to handle the reversal and call it from main.
    Well, that might serve to test the algorithm, and might be appropriate for a Java programmer learning Groovy, but for Groovy beginners, that public class stuff and public static void main() stuff just serve to clutter up the landscape.

    Quote Originally Posted by Starstreak
    Declare your array in main as follows: char[] band = { 'I', 'N', 'X', 'S' };
    OK for Java; won't work in Groovy. (Have you tried it?)

    Quote Originally Posted by Starstreak
    (Bear in mind that a char [] uses single quotes ' ' and not " " <-- those are for Strings.)
    In Groovy, there are no character literals. Single quotes indicate String literals. Double quotes also indicate String literals. Strings with length = 1 are "coerced" into character constants. So your second example works in Groovy with single quotes or double quotes around the initialization array members. The code from the OP was missing the "new" and that's the only thing about his array declaration/initialization that needed fixing. I'll give the Groovy alternative that looks "almost" like your first example in a minute.

    Quote Originally Posted by Starstreak
    Ideally you would need a loop to print the result to see if it is correct.
    Why would you say that you need a loop to print an array of char?

    In Groovy you don't need a loop. You don't even need System.out. You don't even need parentheses. Heck, you don't even need a semicolon
            // Groovy print statement to print out the contents of an array of char looking like a String
            println "band = " + band

    I mean, you can put in all of that Java-looking stuff if you want to (as I showed in my example of debugging print statements). Many Java constructs and much Java syntax is "forward-compatible" with Groovy. (And that's not a coincidence.)

    Semicolons at the end of statements are optional in Groovy. People with previous experience in languages like C and C++ and Java tend to put them there by force of habit, but they serve no purpose in Groovy itself.


    Here's a complete Groovy program except I deleted the part in the function that does the work that assignment expects:
    // Groovy program demonstrating two ways to reverse
    // the elements of an array of char.
    // First way uses List reverse method.
    // Second way uses method defined in this program.
    // 
    //   Zaphod_b
    //
     
    // Note array initialization syntax differs from Java!
    //
    // Note that arrays of char get printed as if they
    // contained a String.
    char [] band = ["I", "N", "X", "S"]
    println "Original            : band = " + band
     
    // Not what the assignment asked for, but I'll show
    // it just for the heck of it.  Don't turn this in!
    // It is not what your instructor wants to see.
    //
    band = Arrays.asList(band).reverse()
    println "After List.reverse(): band = " + band
     
    // Without any extra class stuff, it uses the locally-defined
    // function.
    //
    // If you wanted to emphasize the local-ness, you
    // could write it like the following:
    // band = this.reverse(band)
    //
    band = reverse(band)
    println "After this.reverse(): band = " + band
     
    //
    // Locally-defined function to reverse elements in an array of chars
    //
    def char [] reverse (char [] favband) {
        //
        char [] whatever// Put your stuff here...
        // Put your stuff here
        // Put your stuff here
        return whatever
    }

    Output:
    Original            : band = INXS
    After List.reverse(): band = SXNI
    After this.reverse(): band = INXS


    Maybe that can be used as a starting point and a testbed.


    Bottom line: Although Groovy accepts a lot of Java-looking syntax and some of it even works the way that Java programmers expect, Groovy != Java (If your grandad knows Java, and you show him Groovy, he may even say that it's "Groovy, man!" like we used to say about cool stuff in the 1960's.)

    To the Original Poster: Sometimes the first one is the hardest. Once you get the program to compile and print some output, then, if the output is wrong, debugging becomes a "snap." The hard part is when it won't compile or it compiles but crashes before printing anything useful. Debugging "nothing" is harder than debugging "somthing."


    Cheers!

    Z
    Last edited by Zaphod_b; October 17th, 2012 at 07:09 PM.

Similar Threads

  1. How to call a C sort function to sort a Java Array.
    By Dwere13 in forum Java Native Interface
    Replies: 22
    Last Post: July 12th, 2012, 04:44 PM
  2. REVERSE ENGINEER AN APK TO UNDERSTAND ITS FUNCTION
    By ANIME in forum Android Development
    Replies: 2
    Last Post: July 4th, 2012, 09:51 PM
  3. Method to take in a string sentence and reverse the tokens
    By ksahakian21 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 25th, 2012, 05:11 PM
  4. [SOLVED] Method to reverse String using While Loop
    By Montrell79 in forum Loops & Control Statements
    Replies: 2
    Last Post: February 22nd, 2012, 03:49 PM
  5. Reverse character using void method
    By bgwilf in forum Algorithms & Recursion
    Replies: 2
    Last Post: December 8th, 2010, 07:25 AM

Tags for this Thread