Results 1 to 2 of 2
Thread: Method not returning a value
- 11-28-2012, 04:00 PM #1
Member
- Join Date
- Nov 2012
- Posts
- 3
- Rep Power
- 0
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...
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.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); }
-
Re: Method not returning a value
You need to assign the value returned by your method to the variable. e.g.,
andJava Code:trialNumber = promptForTrialNumber();
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.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; }
Similar Threads
-
Returning get() method in put() method in a Hash Map
By Wpbops in forum New To JavaReplies: 1Last Post: 12-15-2011, 04:02 AM -
My method keeps returning 0
By ToolJob in forum New To JavaReplies: 11Last Post: 03-27-2011, 05:22 PM -
Returning Value from a method
By Mirix in forum New To JavaReplies: 12Last Post: 06-01-2010, 09:48 PM -
returning an object from a method
By bigj in forum New To JavaReplies: 7Last Post: 01-08-2010, 12:39 PM -
Need help. Method won't returning proper value..
By zlwilly in forum New To JavaReplies: 2Last Post: 12-02-2008, 09:44 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks