Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Java stuff. :X
#1
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
Reply
#2
Code:
public double averageOfNumbers(int[] numbers)
{
  double x=0;
  for(int i=0; i<numbers.length; i++)
  {
  x += numbers[i];
  }
  return x/numbers.length;
}

You're originally returning the total of the numbers.
Reply
#3
Oh. Dang, simple error. I was seriously going crazy over how I was screwing up on it. Now I feel dumb. :X Thanks Joe.
Reply
#4
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! :D
f (x) {
   if (x == 0)
     return 0
   else {
     y = x % 10
     z = f((x - y)/10)
     return(y + z)
   }
}

Eventually, the code can be optimized extremely, but this is the initial theory behind.
Reply
#5
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. :]
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)