[英]Java - Function does not return what I expected
Here's the code: 这是代码:
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
String string1 = "randomString1";
System.out.print(f(string1));
}
public static int f(String string)
{
try {
String string2 = "randomString2";
if(string.equals(string2) == true);
return 0;
}
catch(Exception e){
e.printStackTrace();
}
return 1;
}
}//end of class
Now, the output of this program is 现在,这个程序的输出是
0 0
But I expected it to be: 但我预计它会是:
1 1
Because what I wanted the f
function to do was to return 0
if the strings were the same and 1
if they weren't. 因为我希望f
函数做的是如果字符串相同则返回0
如果不相同则返回1
。
So, there's definitely something I know wrong here, and I'm guessing it has something to do with the equals
method. 所以,这里肯定有一些我知道的错误,我猜它与equals
方法有关。
this is the problem: 这就是问题:
if(string.equals(string2) == true);
----------------------------------^
you'll need remove the semi-colon else, it is pretty much an expression on its own doing nothing: 你需要删除它的分号,它几乎是一个表达它自己什么都不做:
if(string.equals(string2) == true) return 0;
if(string.equals(string2) == true);
you have a semicolon there which does not belong. 你有一个不属于的分号。 Honestly you don't even need the == true
part as well. 老实说,你甚至不需要== true
部分。
because of the semi-colon in the end of your if : 因为你的if结尾有一个分号:
if (string.equals(string2) == true);
//---------------------------------^
return 0;
So when you make a semi-colon in the end of if mean that a statement is end start a new statement which is return 0
for that you get 0
and not 1
所以当你在结尾处做一个分号时,如果意味着一个语句结束,则开始一个新的语句, return 0
表示你得到0
而不是1
to understand more, what did you have mean this : 要了解更多,你有什么意思:
if (string.equals(string2) == true){
//do nothing
}
//pass to the next statement
return 0;
So instead you can use : 所以你可以使用:
if (string.equals(string2)){
return 0;
}
man... 男人...
if(string.equals(string2) == true);
The semi-colon (;) this prevents the code to go inside the if block, and hence the 分号(;)这可以防止代码进入if块内部,从而阻止代码进入
return 0;
line executes and returns 0 line执行并返回0
The program works fine as it should. 该程序正常工作。
The solution to your problem... 你的问题的解决方案......
if(string.equals(string2))
return 0;
Remove the semi-colon.. the code would work fine. 删除分号..代码可以正常工作。
You have an unnecessary semilocon at the end of your if statement. 你在if语句的末尾有一个不必要的semilocon。 Try below option: 请尝试以下选项:
if(string.equals(string2)) {
return 0;
}
Simplified. 简化。
public static int f(String string)
{
String string2 = "randomString2";
return (!TextUtils.isEmpty(string) && string.equals(string2)) ? 0 : 1;
}
No need of try-catch as TextUtils will handle null for string. 不需要try-catch,因为TextUtils将为字符串处理null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.