Search code examples
javamethodstypesreturnhelper

Return statement in Helper Method(Java)


I am practicing simple coding problems from codingbat. One of the problems are asking me to use helper method to prevent redundant codes. However, I am very lost because I do not know why I should use public and int as return type for this problem.(because the question asks me to use header below)

public int fixTeen(int n)

What does the return from the helper method doing? Also, how do I know if I should use private or public for my helper method?

Please take a look at my code.

// Given 3 int values, a b c, return their sum. However, if any of the values 
// is a teen -- in the range 13..19 inclusive -- then that value counts as 0, 
// except 15 and 16 do not count as a teens. Write a separate helper 
// "public int fixTeen(int n) {"that takes in an int value and returns that value 
// fixed for the teen rule. In this way, you avoid repeating the teen code 3 
// times (i.e. "decomposition"). Define the helper below and at the same 
// indent level as the main noTeenSum().
public int noTeenSum(int a, int b, int c) {
  return fixTeen(a) + fixTeen(b) + fixTeen(c);
}
public int fixTeen(int n) {
  if (n >= 13 && n <= 19 && n != 15 && n != 16)
    n = 0;
  return n;
}

Edit: What is the difference between setting return type void and int for the helper method? At first, I thought return int is unnecessary and tried to set the return type as void but it gave me an error.


Solution

  • In general, at least for the beginnings of java, methods should be named public. Later on, when you get to object oriented programming, the area it's in (public or private) matters more. For example, adding the keyword "public" means that that value can be accessed outside of the class, while "private" means it cannot. This is important for when you don't want the end user to be able to access your private data.

    Point is, when you make a method, for now have them set to public.

    Next up is the helper method. After the "public" or "private", you have the return type. You have it set to "int". Therefore, the return type must be an integer. It can't be a string, or a double - it must be an integer. If you set the return value to "void", then there would be no return value, and if you tried to write "return(n);", it would give you an error.

    So TLDR: It's named "public" because you want to be able to access this method outside of the class, and it says "int", because you need to return an integer type. Then, when you return(n), it'll give the value, say, a == 7, and if b == 18, it'll set b == 0. After that, it adds the numbers together, and you have your answer!