【发布时间】:2021-02-09 07:26:01
【问题描述】:
我正在使用codingbat 练习简单的编码问题。其中一个问题是要求我使用helper method 来防止冗余代码。但是,我很迷茫,因为我不知道为什么我应该使用public 和int 作为这个问题的返回类型。(因为问题要求我使用下面的标题)
公共 int fixTeen(int n)
辅助方法的返回值是做什么的?另外,我如何知道我应该使用 private 还是 public 作为我的辅助方法?
请看一下我的代码。
// 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;
}
编辑:
为辅助方法设置返回类型void 和int 有什么区别?起初,我认为return int 是不必要的,并尝试将返回类型设置为void,但它给了我一个错误。
【问题讨论】:
-
如果您使用了
private,那么只有类中的方法才能使用该方法。
标签: java methods types return helper