简体   繁体   中英

How to access methods in java from other methods?

I'm very new to programming. However, I've written a method called "succ" that's adds 1 to a given parameter. It looks like this:

int succ(int x) {
  return x += 1;
}

Now I'm supposed to write another method that adds 2 numbers using my first method. This is what my attempt looks like:

int add(int x, int y) {
  for(int i = 0; i < y; i++) {
    succ(x);
  }
  return x;
}

Unfortunately it doesn't seem to work; it always returns the initial x. For example: If I type add(8,5) it just returns 8. Can someone help me? What am I doing wrong?

Thanks in advance.

You're not doing anything with the returned value. If you want to assign it back to x , do that:

x = succ(x);

Edit: Or, perhaps you mean to add to x , since you're doing it in a loop? It's not entirely clear what this code is meant to do, and I suspect more applicable variable/method names would help. But if you want to keep adding the result, you'd just do this:

x += succ(x);

Additionally, you don't need to modify x in your succ function. Doing so in this manner may lead to unexpected behavior in the future in other examples. Keep the operations as simple as possible. Just return the calculated value:

return x + 1;

You are missing the return value of the succ method, replace the succ(x); with x = succ(x);

int add(int x, int y) {

  for(int i = 0; i < y; i++) {
    x = succ(x);
  }
  return x;
}

You keep overwriting the x value with the return value from the function. You need to add to it in each iteration, not overwrite it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM