bzu*_*ick -1 java string equality
可能重复:
Java中的字符串比较
继承我的剧本:
public class euler4 {
/**
* a palindromatic number reads the same both ways. the largest palindrome
* made from the product of 2-digit numbers is 9009 = 91 * 99.
*
* find the largest palindrome made from the product of two 3-digit numbers.
*/
public static void main(String[] args) {
/*for(int t = 100; t < 200; t++) {
for(int l = 100; l < 100; l++) {
String milah = "" + t * l;
String result = palin(milah);
if(result != "no_pali") {
System.out.println(milah);
}
}
} */
String result = palin("abba");
System.out.println(result);
}
public static String palin(String the_num) {
int orech = the_num.length();
String back_word = "";
/**
* the for loop has the counter starting at the orech of the number, then
* decrementing till 0 (or the 0'th index)
*/
for(int i = orech - 1; i >= 0; i--) {
back_word = back_word + the_num.charAt(i);
}
System.out.println(the_num);
System.out.println(back_word);
System.out.println(back_word == "abba");
if(back_word == the_num) {
return back_word;
} else {
return "no_pali";
}
}
}
Run Code Online (Sandbox Code Playgroud)
在第34行,它打印"abba"就像它应该的那样
在第35行,它打印出"abba"的精确副本
它在第36行变得奇怪,这是:
System.out.println(back_word == "abba");
Run Code Online (Sandbox Code Playgroud)
那打印假..... ??
它打印出精确的文字副本,但是当我比较它们时,它会给出错误!?
因为它们不相等(当它们确实这样做时)它返回了错误的东西
Dra*_*kar 19
在java中,==运算符比较对象的地址.
要比较两个字符串是否相等,您需要使用该.equals()函数.
back_word.equals("abba");
Run Code Online (Sandbox Code Playgroud)
使用back_word.equals("abba");代替。
==在Java中测试它们是否是同一对象,以便back_word == back_word返回true。
字符串类的.equals方法但是检查
如果给定的对象表示等效于此字符串的String,则返回false