Java输入问题-如何比较字符串 [英] Java Input Problems - how to compare strings
问题描述
这似乎很简单,但是我已经在这里停留了几个小时.
This seems to be pretty simple, but I have been stucked here for a couple of hours.
当您必须比较Java中的两个字符串时,我感到怀疑.
I have a doubt when you have to compare two Strings in Java.
如果我只是这样做:
String var1 = "hello";
String var2 = "hello";
然后在另一个函数中比较这两个单词,结果显然是正确的.
and then compare these two words in another function, the result will clearly be true.
但是问题是当我必须比较来自输入的两个单词时.这是我的代码:
But the problem is when I have to compare two words that come from an input. Here is my code:
import java.util.Scanner;
public class Compare{
public static void main(String[] args){
Scanner Scanner = new Scanner (System.in);
System.out.println("Enter first word: ");
String var1 = Scanner.nextLine();
System.out.println("Enter second word: ");
String var2 = Scanner.nextLine();
if (same (var1, var2))
System.out.println("Yes");
else
System.out.println("No");
}
public static boolean same (String var1, String var2){
if (var1 == var2)
return true;
else
return false;
}
}
我尝试了几次(显然输入了相同的单词),结果始终是False.
I have tried several times (clearly entering the same word) and the result is always False.
我不知道为什么会这样.我想念什么?
I don't know why this happens. What am I missing?
这是我第一次使用Java.我将不胜感激.谢谢
This is my first time in Java. I will appreciate any kind of help. Thanks
推荐答案
您应该更改
if (var1 == var2)
{
return true;
}
else
{
return false;
}
到
if (var1.equals(var2))
{
return true;
}
else
{
return false;
}
有关两者之间的区别,请参见此答案.
See this answer for the difference between the two
这篇关于Java输入问题-如何比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!