如何编写一个对某些参数返回 True 的私有方法?
所以准确的写法是 “编写一个私有方法 isValid(aRating),如果给定的评级有效(介于 1-10 之间),则返回 true。”
private void isValid(aRating)
{
}
如果给定的评级有效,则上述方法中的内容是为了返回真值,“有效性”表示数字 1-10。
这就是我尝试的,教练希望它是“正确的方式”,这只是我尝试的一个例子,它是一个完全不同的程序。(如果令人困惑,请忽略)。
private void isValid(int hour, int minute)
{
if (hour >= 0 && hour <=23)
{
System.out.println("Hour is valid");
hourIsValid = true;
}
else
{
System.out.println("Hour is not valid");
hourIsValid = false;
System.exit(0);
}
}
这是正确的吗
private boolean isValid(int aRating)
{
if (aRating >= 1 && aRating <= 10)
return true;
else
return false;
}
So the exact wording is,
"Write a private method isValid(aRating) that returns true if the given rating is valid, which is between 1-10."
private void isValid(aRating)
{
}
What Goes in the Method above in order to return a true value if given rating is valid, Validity meaning a number 1-10.
This is what i attempted, the instructor wants it the "proper way" This is just an example of what i attempted at, It is a different program completely.(Ignore if confusing).
private void isValid(int hour, int minute)
{
if (hour >= 0 && hour <=23)
{
System.out.println("Hour is valid");
hourIsValid = true;
}
else
{
System.out.println("Hour is not valid");
hourIsValid = false;
System.exit(0);
}
}
Would this be correct
private boolean isValid(int aRating)
{
if (aRating >= 1 && aRating <= 10)
return true;
else
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该问题要求函数在某些条件下返回 true,因此签名不能
需要返回类型。现在,
true
的类型是布尔值,所以将其设置为The problem demands a function that returns
true
under some conditions, so the signature cannot beit needs a return type. Now,
true
's type is boolean, so make it调用私有方法
从公共方法调用私有方法与调用任何其他方法完全相同:
重要的区别在于,您只能从定义私有方法的类内部调用私有方法:
返回值
这种方法的问题在于:如果您输入错误的小时或分钟,您的程序会立即终止。如果我想循环直到获得良好的输入怎么办?
我认为主要问题是您不知道如何 返回值来自方法。下面是一个始终返回
true
的函数示例:您还可以使其变得更复杂:
如果
num
位于以下位置,则该函数将返回true
范围 10-20 和false
否则:此版本完全相同做同样的事情,但您可能会发现它更容易阅读,因为它更明确:
如果不是,请告诉我足以帮助您解决问题。
Calling Private Methods
Calling a private method from a public one is exactly the same as calling any other method:
The important difference is that you can only call private methods from inside the class where they were defined:
Return Values
The problem with this approach is that your program immediately dies if you input a bad hour or minute. What if I want to loop until I get a good input?
I think the main problem is that you don't know how to return a value from a method. Here's an example of a function that always returns
true
:You can also make it more complicated:
Here's one that will return
true
ifnum
is in the range 10-20 andfalse
otherwise:This version does exactly the same thing, but you may find it easier to read since it's more explicit:
Let me know if that's not enough to help you with your problem.
就像您可以调用任何普通方法一样,只要私有方法对公共方法可见即可。
Just like you would call any normal method as long as the private method is visible to the public method.