Vswe's Summer Courses | You're not logged in. Sign up or log in | Server time: | Donate
One can now see other persons' badge hunts. Simply head over to their profiles to access them.

Go back to sub forum page

General forum

Non-course related subjects

3. Programming help

Save an array in a method

  • 2013-12-24 19:02:45
    When I run this code:

    static int[] basketcontent(int seq, int quantity){
            int[] basket = new int[4];
            switch(seq) {
                case 0:
                    basket[0] = basket[0] += quantity;
    it does't save the value of array basket it prints out the value that I typed in to my program.
    so for example if i typed in 2 and when it goes a second time through this method with this particular parameters and I typed in 2 again it just gives me 2 so it doesn't remember it. Is there any way to fix this?
  • 2013-12-25 14:48:48
    You are creating a new array everytime you run the method, so you get a {0, 0, 0, 0} because you have this inside your method: int[] basket = new int[4];
    You need to use a global variable basket like this:
    Public static int[] basket = new int[4];
    public static int[] blahblahblah(.....) {
  • 2014-01-05 12:55:53
    Global variables can get icky.
    Depending on what you're looking to do, you might want to instead pass the array itself as an argument in your parameters.
    Example here:

    static void basketContent(int seq, int quantity, int[] basket){
    case 0:

    When you pass an array as an argument, you don't clone the array for the method, rather you pass a reference (which in Java is passed as a value that IS the reference) so changes made in the method affect the array when the method completes.
  • Log in or sign up to reply to this thread