【问题标题】:Return statement in Helper Method(Java)Helper Method(Java) 中的返回语句
【发布时间】:2021-02-09 07:26:01
【问题描述】:

我正在使用codingbat 练习简单的编码问题。其中一个问题是要求我使用helper method 来防止冗余代码。但是,我很迷茫,因为我不知道为什么我应该使用publicint 作为这个问题的返回类型。(因为问题要求我使用下面的标题)

公共 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;
}

编辑: 为辅助方法设置返回类型voidint 有什么区别?起初,我认为return int 是不必要的,并尝试将返回类型设置为void,但它给了我一个错误。

【问题讨论】:

  • 如果您使用了private,那么只有类中的方法才能使用该方法。

标签: java methods types return helper


【解决方案1】:

一般来说,至少对于java的开始,方法应该被命名为public。稍后,当您开始进行面向对象编程时,它所在的领域(公共或私有)更为重要。例如,添加关键字“public”意味着该值可以在类外部访问,而“private”意味着它不能。当您不希望最终用户能够访问您的私人数据时,这一点很重要。

重点是,当你创建一个方法时,现在将它们设置为 public。

接下来是辅助方法。在“public”或“private”之后,你有返回类型。您已将其设置为“int”。因此,返回类型必须是整数。它不能是字符串或双精度 - 它必须是整数。如果将返回值设置为“void”,则没有返回值,如果尝试写“return(n);”,则会报错。

所以 TLDR:它被命名为“public”,因为您希望能够在类之外访问此方法,它说“int”,因为您需要返回一个整数类型。然后,当你 return(n) 时,它会给出值,比如 a == 7,如果 b == 18,它会设置 b == 0。之后,它将数字相加,然后你有你的答案!

【讨论】:

    猜你喜欢
    • 2011-01-03
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2015-05-03
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多