Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Sending arrays to method help

    I cannot figure out how to return the array back to the main method!
    what am I doing wrong??


    import java.util.*;

    //lab 3

    public class Prices
    {
    public static void main(String[] args)
    {
    double []array;
    array = new double[10];

    double fullPrice;

    fullPrice = fillPrices(array);

    System.out.println("testing");
    }

    public static double fillPrices(double []tenValues)
    {
    Scanner input = new Scanner(System.in);
    double prices;


    System.out.println("Please enter 10 prices: ");

    for (int i = 0; i < 10; i++)
    tenValues[i] = input.nextDouble();

    return tenValues;
    }
    }

    I thought you return an array by simply return (array name);

    Am i missing something?

    Thanks a bunch for whoever takes the time to help me!

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,688
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    This is the javaSCRIPT forum.

    Your code is written in JAVA.

    About the only thing the two languages have in common are the first four letters of their names.

    ***********

    Having said that... this problem is obvious.

    Code:
    double fullPrice;
    
    fullPrice = fillPrices(array);
    If your fillPrices function returns an array, then *HOW* can you assign an array to a variable that is only one double value?

    But, actually, there is no reason to return anything from your function: Since you create the array in main and passed it to the function, then when the function is done, the array created in main *will* be filled in.

    In Java, arrays are passed by reference, not by value, so if you change their contents, you change them both in the function and in the caller of the function.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    alright, figured it out! thanks for the help and sorry for the ignorance...


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •