![]() |
|
Simple Java stuff. :X - Printable Version +- Southperry.net (https://www.southperry.net) +-- Forum: Social (https://www.southperry.net/forumdisplay.php?fid=14) +--- Forum: Rubik's Cube (https://www.southperry.net/forumdisplay.php?fid=58) +--- Thread: Simple Java stuff. :X (/showthread.php?tid=20396) |
Simple Java stuff. :X - mrcowcow - 2009-12-13 Alright so I have to create two methods. I've only learned basic Java so I'm kind of a dumbass at working arrays and stuff. In my first method, I have to pass an integer into a method, and use the method to find the sum of the digits. I have no idea in hell how I'm supposed to even start doing this. :X The second method is kind of annoying me; I can't figure out what the heck I'm doing wrong. A tester that was given to us is telling me that I did it wrong. It might be just because I don't even know how to work arrays well at all. public double averageOfNumbers(int[] numbers) { double x=0; for(int i=0; i<numbers.length; i++) { x += numbers[i]; } return x; } Thanks in advance guys. I'm just a beginner at Java. :X Simple Java stuff. :X - JoeTang - 2009-12-13 Code: public double averageOfNumbers(int[] numbers)You're originally returning the total of the numbers. Simple Java stuff. :X - mrcowcow - 2009-12-13 Oh. Dang, simple error. I was seriously going crazy over how I was screwing up on it. Now I feel dumb. :X Thanks Joe. Simple Java stuff. :X - Nikkey - 2009-12-13 mrcowcow Wrote:In my first method, I have to pass an integer into a method, and use the method to find the sum of the digits. I have no idea in hell how I'm supposed to even start doing this. :X There are (at least) two ways of doing this: Turn the integer into a string, then go through each character in the string, and sum them up through convertion. Or think this way: let us call the function we're naming for f, with input int x. If x = 0, then return 0, otherwise, return the "tenth" plus f((x - tenth)/10). This can be written as this: (I assume you know discrete mathematics?) Code: //Pseudo. I'll not doing your homework, think for yerself! :DEventually, the code can be optimized extremely, but this is the initial theory behind. Simple Java stuff. :X - mrcowcow - 2009-12-13 Thanks Devil's Sunrise. I was initially doing it the way you described, and then someone directed me to the Java APIs, which made my life a whole lot easier. :O Thanks for your help though. :] |