[英]Why does the default Boolean return value influence my tests outcome
I'm learning Java and while completing exercises I stumbled upon an issue in CodingBats sameStarChar program. 我正在学习Java,并在完成练习时偶然发现CodingBats sameStarChar程序中的一个问题。
I know this is a simple exercise but the logic behind the different outcome is really bugging me. 我知道这是一个简单的练习,但是不同结果背后的逻辑确实困扰着我。
When I write : 当我写:
public boolean sameStarChar(String str) {
for (int i = 1; i < str.length() - 1; i++) {
if (str.charAt(i) == '*') {
if (str.charAt(i - 1) != str.charAt(i + 1))
return false;
}
}
return true;
}
All results are OK. 所有结果都还可以。
But when I change the code and invert the condition in the if
block and return false
as default return value, the code does not work anymore and some test fail: 但是,当我更改代码并反转
if
块中的条件并返回false
作为默认返回值时,该代码不再起作用,并且某些测试失败:
public boolean sameStarChar(String str) {
for (int i = 1; i < str.length() - 1; i++) {
if (str.charAt(i) == '*') {
if (str.charAt(i - 1) == str.charAt(i + 1))
return true;
}
}
return false;
}
Can you please tell me why are the outcomes different? 您能告诉我结果为何不同吗? I can`t seem to find an exact explanation for this in any book.
在任何一本书中,我似乎都找不到确切的解释。
Pay close attention to what the code is doing, in English: 用英语密切注意代码的作用:
*
: *
:
The reason you get completely different results is because you completely flip the logic of the program. 得到完全不同的结果的原因是因为您完全翻转了程序的逻辑 。 Here's your code, in English again:
这是您的代码,再次使用英语:
*
: *
:
You haven't made false
the default return option; 您没有将
false
为默认的返回选项。 you've inverted the entire program's logic. 您已经颠倒了整个程序的逻辑。 Consider the empty string, which is a valid test case.
考虑空字符串,这是一个有效的测试用例。 Your code said that this is invalid, when there's no asterisk to be had in the string (which would be a strange false positive).
您的代码说,当字符串中没有星号时,这是无效的(这将是一个奇怪的误报)。
The 1st case works because it returns true only if the *
is preceded and followed by the same character or if the string
doesn't contain a *
at all. 第一种情况有效,因为只有在
*
前后带有相同字符或者string
根本不包含*
情况下,它才返回true。
The 2nd case doesn't work because it returns true if it contains at-least one *
and first instance of *
is preceded and followed by the same characters regardless of next instances of *
. 在第二种情况不起作用,因为它返回true,如果它包含至少具有一个
*
和一审*
的前面和后面相同的字符,无论下一个实例*
。 So if a blank string is passed it should return true but it instead returns false because it doesn't contain *
. 因此,如果传递了空白字符串,则应返回true,但返回false,因为它不包含
*
。 If another string *xa*a*b
is passed the second program will return true because the instance of *
follows the convention. 如果传递了另一个字符串
*xa*a*b
则第二个程序将返回true,因为*
的实例遵循约定。 The 2nd Program will return true right away, ignoring all the *
after the it's first appearance. 第二个程序将立即返回true,并在其首次出现后忽略所有
*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.