Java初学者程序帮助(if,else问题)
我正在练习制作自己的字符串反转工具。 为了让学习过程更精彩,我在一个简单的应用程序中使用了该方法。 但是……Java初学者程序帮助(if,else问题),java,if-statement,Java,If Statement,我正在练习制作自己的字符串反转工具。 为了让学习过程更精彩,我在一个简单的应用程序中使用了该方法。 但是…… 当我在Eclipse中运行代码时, 即使单词是=赛车 并且倒转成=赛车(单词倒转)。 此时将显示else。。 告诉我单词和倒数永远不相等。。但是……如果是这样的话?对吗? 请给我一些建议,这真是个麻烦。 多谢各位 import java.util.Scanner; public class Main { static Scanner sc = new Scanner(Syst
当我在Eclipse中运行代码时, 即使单词是=赛车 并且倒转成=赛车(单词倒转)。 此时将显示else。。 告诉我单词和倒数永远不相等。。但是……如果是这样的话?对吗? 请给我一些建议,这真是个麻烦。 多谢各位
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.println("Please enter a word, I'll show it reversed ");
System.out.println("and tell you if it is read the same forward and backward(A Palindrome)!: ");
String word = sc.nextLine();
String reverse = reverse(word);
if (reverse == word){
System.out.println("Your word: " + word + " backwards is " + reverse + ".");
System.out.println("Your word is read the same forward and backward!");
System.out.println("Its a Palindrome!");
}
else {
System.out.println("Your word: " + word + " backwards is " + reverse + ".");
System.out.println("Your word is not read the same forward and backward!");
System.out.println("Its not a Palindrome!");
}
}
public static String reverse(String source){
if (source == null || source.isEmpty()){
return source;
}
String reverse = "";
for(int i = source.length() -1; i >= 0; i--){
reverse = reverse + source.charAt(i);
}
return reverse;
}
}
始终使用来比较字符串<代码>=将在引用相等时进行比较,但由于它们的存储方式不同,这对比较相等的字符串并不起作用
if (reverse.equals(word))
为什么没有显示if的原因是因为不能将==用于字符串。您只能在math/int/double/float等比较中这样做 对于字符串比较,必须使用
equals(String s)
或者对于不必完全相同大小写的单词
equalsIgnoreCase(String s)
在Java中,对象(包括字符串)作为引用存储——它们在内存中的位置
=
运算符检查这些引用是否相等,而不是实际字符串是否相等
幸运的是,Java有一个解决方法。如果两个字符串的内容相同,String方法
equals(String)
将返回true。将其用于字符串,而不是=
您应该使用equals方法来比较两个字符串,字符串是一个对象,这是一个引用,equals()方法将比较两个字符串的内容,但是==将比较两个字符串的地址
所以,你应该这样写:
if (reverse.equals(word))
嗯。。。这些方法并不存在。使用
a.equals(b)
或a.equalsIgnoreCase(b)
。这就是我想说的,与其他东西混淆了,谢谢你的更正!哇!非常感谢你!别开玩笑了,我知道。。我忘了O@AndrewFabian如果你觉得答案能解决你的问题,你应该接受。谢谢大家的帮助!我知道String.equals(String),但我用它来做菜单之类的事情。所以我用if(“yes”。equals(input)){我觉得自己很笨。没问题!很高兴我帮了忙。