Results 1 to 2 of 2
  1. #1
    mathwiz7 is offline Member
    Join Date
    Nov 2012
    Posts
    3
    Rep Power
    0

    Default Method not returning a value

    This should be a simple problem...I can't figure out what I'm doing wrong. I'm only trying to have a new method return the value I just typed but it doesn't seem to work. Here's what I have...

    Java Code:
    public static int promptForTrialNumber(int t)
        {
            System.out.print("How many darts/trials? ");
            Scanner in = new Scanner(System.in);
            t = in.nextInt();
            return t;
        }
        public static void main()
        {
            int trialNumber = 0;
            promptForTrialNumber(trialNumber);
            System.out.println(trialNumber);
             
        }
    The code just prints out 0 instead of the number I had just typed...It's not an issue with the scanner as I inserted a println in the promptForTrialNumber method after the in.nextInt() and before the return statement and that returned the value typed.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Method not returning a value

    You need to assign the value returned by your method to the variable. e.g.,

    Java Code:
    trialNumber = promptForTrialNumber();
    and
    Java Code:
        // get rid of the parameter
        public static int promptForTrialNumber()
        {
            System.out.print("How many darts/trials? ");
            Scanner in = new Scanner(System.in);
            int t = in.nextInt();
            return t;
        }
    Note that Java is passes parameters by value always, so that passing your variable into the method won't work since it's a primitive variable. Even if it did work, it's a bad habit to get into since you'll be changing state by side effect rather than by assignment, making your code much harder to debug.

Similar Threads

  1. Replies: 1
    Last Post: 12-15-2011, 05:02 AM
  2. My method keeps returning 0
    By ToolJob in forum New To Java
    Replies: 11
    Last Post: 03-27-2011, 06:22 PM
  3. Returning Value from a method
    By Mirix in forum New To Java
    Replies: 12
    Last Post: 06-01-2010, 10:48 PM
  4. returning an object from a method
    By bigj in forum New To Java
    Replies: 7
    Last Post: 01-08-2010, 01:39 PM
  5. Need help. Method won't returning proper value..
    By zlwilly in forum New To Java
    Replies: 2
    Last Post: 12-02-2008, 10:44 PM

Posting Permissions

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